I have been trying so hard to filter my records by ID from MongoDB without success. The problem is with $oid
On MLAB my records look like :
{
"_id": {
"$oid": "57603891dcba0f7813102b3f"
},
"age": 10,
"name": "john",
"answer": "3",
}
My script as:
mycollection.find({_id:"57603891dcba0f7813102b3f"},{},{},function(err, docs) {
console.log("record"+docs);
docs.each(function(err, doc) {
if(doc) {
console.log("record"+doc);
}
});
});
What is wrong in it? any idea guys?
The issue with your script is that you are trying to compare a normal string "57603891dcba0f7813102b3f"
with a ObjectId string
{
"$oid": "57603891dcba0f7813102b3f"
},
If you are using Node.Js, here's what you can do
1) Import ObjectId api from mongodb package
var ObjectId = require('mongodb').ObjectID;
2) Convert normal string to ObjectId in your query
mycollection.find({_id:ObjectId("57603891dcba0f7813102b3f")},{},{},function(err, docs) {...}
Btw, The answer posted by @titi23 also works. But i find ObjectId conversion a cleaner approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With