5

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?

Community
  • 1
  • 1
soulemane moumie
  • 1,005
  • 1
  • 14
  • 26

4 Answers4

11

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.

Kavya Mugali
  • 1,008
  • 2
  • 10
  • 17
9

You can search on mLab in this way.

{
    "_id": {
        "$oid": "59b59b34852a9619b486634f"
    }
}

But your javascript code should be,

uId = ObjectId("59b59b34852a9619b486634f")
User.findOne({"_id": uId}, function(err, user){
});
satato
  • 116
  • 1
  • 4
0

Try the following :-

 mycollection.find({"_id.$oid":"57603891dcba0f7813102b3f"},{},{},function(err, docs) {
console.log("record"+docs);
docs.each(function(err, doc) {
  if(doc) {
    console.log("record"+doc);
  }
});
  });
Shrabanee
  • 2,706
  • 1
  • 18
  • 30
0

On your local development MongoDB server, the "_id" is indexed and identified using ObjectID("...."). For example, when querying locally you may get

{ "_id": ObjectID("....") , "name": ".......", "password" : "............"}

while querying in Mlab or any remote mongodb server, the "_id" is referenced as "$oid". For example,

{ "_id": { "$oid": "..........."} , "name": "......."}

If you are like me, you may try to edit the document's "_id" in MLab and replace the former description with the latter, Mlab won't allow you to do such, i think that's part of its restrictions. Try it out and see if you have any workarounds to share.

chikeozulumba
  • 21
  • 1
  • 2