orlandos-nl / MongoKitten

Native MongoDB driver for Swift, written in Swift

Home Page:https://orlandos.nl/docs/mongokitten/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to check if ObjectId exist in collection

sergeydi opened this issue · comments

Hi,
Could you please help, 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?

In MongoKitten 4:

let document = try collection.findOne("_id" == <my-objectId>)

In MongoKitten 5:

collection.findOne("_id" == <my-objectId>).then { document in 
    ...
}

@Joannis <my-objectId> must be String value of objectId or some objectId value?

An ObjectId value in your case. try ObjectId("5bb216a8475fe42644993a40") would produce a static one.

Realistically an _id key in MongoDB can contain any value you wish to put there including string, integer, document, double and many others, as long as it's unique. So a user might have it's email address under the _id key, but you don't apparantly :)

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 is nil in any case (ObjectId exist and not exist)

Are you reading through the right collection/database? Try creating a server instance first using the string and then explicitly selecting the database using the subscript.

let client = try MongoKitten.Server("mongodb://\(username):\(password)@\(ipAddress)")
let myCollection = client[database][collection]

It was error on my side. Thank you. Everything works perfect :)

Also, how to get the same result using find method, because findOne takes much more resources than find method?

It does not, findOne does not take any more resources since they're the same command.

for document in collection.find("_id" == oid, limitedTo: 1) {
  print(document) // only executes once
}

The above will be the same performance and everything, but will have more (complex) code.

When I mean findOne is the same thing as find, I really mean the same thing

Thank you :)