Searching MongoDB by the auto '_id' field, not possible?
I am trying to query MongoDB and find the row which has a specific '_id' but I can not do that. When I write for example:
$r = $cursor->getNext();
and debug, I find the value of $r['_id'] is empty. Not null, but empty! Any idea why this happens and how to avoid it? Using PHP
Update:
I was able to retrieve the '_id' by $curso开发者_JS百科r->key()
but still I can't query and I wonder why the reason behind that!
I would bet that the reason is that you are not using the MongoId class.
I was able to retrieve the '_id' by $cursor->key()
but still I can't query and I wonder why the reason behind that!
You need to be careful to avoid RDBMS thinking. The ObjectID is not a primary key. Bear in mind that MongoDB evolved as an answer to handle the problem posed by "Big Data". This means lots and lots of data, possibly hundreds of thousands of entries each day ... you get the picture. Accordingly, ObjectID represents a pseudo-random key which allows rapid inserting of data without having to find the RDBMS equivalent of "last insert ID".
If you are really keen to use _id as an equivalent to an RDBMS primary key, just overwrite it when inserting the document in the first case:
db.collection.insert({_id:100,name:"Joe",balance:200.18})
You could then easily find this document as follows:
db.collection.find({_id:100})
But you might start to run into scalability problems ... and then you're back to the problem of how do you determine which is the next key to generate. Also, _id must be unique. If you accidentally add a new document with the same _id as an existing document, you'll get a "duplicate key" error when using insert(). If you add a document using save() and _id already exists, you'll end up overwriting the data on the existing document!
More thoughts later ...
精彩评论