MongoKitten:检查ObjectId是否存在

时间:2018-10-02 08:18:21

标签: swift mongokitten

如何检查集合中是否存在ObjectId? 从mongo控制台执行此操作:

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

如何使用MongoKitten做同样的事情?

1 个答案:

答案 0 :(得分:1)

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