4

I have an array which contains Id of a mongodb collection

array = [ '573163a52abda310151e5791',
         '57358e5dbd2f8b960aecfa8c',
         '573163da2abda310151e5792' ]

like this, in my nodejs code I want to find the documents of all these Ids. the package I'm using is mongoskin.

according to the docs this is the correct way to find the result, which is giving me what I want. But here instead of direct values I want to use the array, but unable to find out how to do that

   db.coll.find({
                _id: {
                    $in: [mongoskin.helper.toObjectID("573163da2abda310151e5792"),
                          mongoskin.helper.toObjectID("57358e5dbd2f8b960aecfa8c"),
                          mongoskin.helper.toObjectID("573163a52abda310151e5791")
                    ]
                }
            }).toArray(function(err, docs) {
                console.log(docs);
                res.send(docs)
            });
Ankit
  • 500
  • 4
  • 21

2 Answers2

4

I don't know much about mongoskin but may be you can try this...

var newArray = oldArray.map(function(ele) {
  return mongoskin.helper.toObjectID(ele);
});
OR
var newArray = oldArray.map(mongoskin.helper.toObjectID(ele));

So now you may use newArray in your query

db.coll.find({
            _id: {
                $in: newArray
            }
        }).toArray(function(err, docs) {
            console.log(docs);
            res.send(docs)
        });
Lahar Shah
  • 5,402
  • 4
  • 20
  • 37
  • thanks it worked, but why the result i'm getting not in the same order as specified in the array. Is it possible to get the result in the same order? – Ankit May 14 '16 at 06:57
2

I think this is useful to you

ObjectID = require('mongoskin').ObjectID;
var array1 = ["5736d1210a39c2547cb9d90e","5736d1380a39c2547cb9d90f]
var array2 = [] 
array1.forEach(function(stringId){
array2.push(new ObjectID(stringId)))
})

then use this array2 variable in query

db.coll.find({
        _id: {
            $in: array2
        }
    }).toArray(function(err, docs) {
        console.log(docs);
        res.send(docs)
    });
karthi
  • 760
  • 5
  • 10