Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB from MLab : find by ID not working

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?

like image 764
soulemane moumie Avatar asked Jun 17 '16 00:06

soulemane moumie


1 Answers

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.

like image 159
Kavya Mugali Avatar answered Sep 28 '22 11:09

Kavya Mugali