swiftmongokitten

MongoKitten: check if ObjectId exist


How to check if ObjectId exist in collection? From mongo console I do it:

> db.collection.find({_id: ObjectId("5bb216a8475fe42644993a40")}, {_id: 1}).limit(1);

How to do the same using MongoKitten?


Solution

  • let mongoClient = try MongoKitten.Database("mongodb://\(username):\(password)@\(ipAddress)/\(database)")
    let myCollection = mongoClient[collection]
    let oid = try ObjectId("5bb216a8475fe42644993a41")
    let document = try myCollection.findOne("_id" ==  oid)
    

    document will be nil if ObjectId not exist

    Also, based on this document, findOne() method of Mongo DB takes much more resources than find() method. But under the hood of MongoKitten findOne() uses find() method: link