0

I have an array of mongoIDs like this

arrayOfIDs = ['mongoID1','mongoID2','mongoID3']

These are mongo-ids of documents in my collection.

Now by taking the an array of those mongoIDs ie ['mongoID1','mongoID2','mongoID3'], I need to query on each of the document specified by those ids, by using its _id and deal with its data independently in my code logic. As an example for simplicity, I have just 'printed' the output ie res.json(doc.name).

I need something like this below If at all it does exist in Mongoose/MongoDB

Shop.find({'_id':['mongoID1','mongoID2','mongoID3']})
    .exec()
    .then(doc =>{
       res.json(doc.name)
    })

I know I can use a loop for this case, like this,

for(id of arrayOfIDs){
    Shop.find({'_id': id})
        .exec()
        .then(doc =>{
           res.json(doc.name)
        })
}

But this involves querying the database multiple times based on the lenght of arrayOfIDs, something I don't want. I would like to have a native mongodb solution that just pass the Ids in mongodb query like in my example above.

Can you please show me how this can be achieved?

1
  • 1
    use $in like this {'_id': { $in: ['mongoID1','mongoID2','mongoID3'] } } Commented Sep 27, 2020 at 15:39

1 Answer 1

1

You can use the $in operator.

{ _id: { $in: ["mongoID1", "mongoID2", "mongoID3"] } }

If the type of _id is ObjectId then you need to convert them to ObjectId before passing it

{
  _id: {
    $in: [
      mongoose.Types.ObjectId("mongoID1"),
      mongoose.Types.ObjectId("mongoID2"),
      mongoose.Types.ObjectId("mongoID3"),
    ],
  },
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.