How do I perform an id array query in Mongoose?


Question

Let's say I have a model called User. I have an array with object Ids.

I want to get all User records that "intersect" with the array of Ids that I have.

User.find({ records with IDS IN [3225, 623423, 6645345] }, function....
1
35
5/9/2016 4:56:19 PM

Accepted Answer

You need to use the $in operator >

https://docs.mongodb.com/manual/reference/operator/query/in/#op._S_in

For example:

Users.find( { "fb" : { id: { $in : arrayOfIds } } }, callback );
35
7/10/2018 2:33:35 PM

Here is a mongoosey way to use the $in operator.

User.find()
  .where('fb.id')
  .in([3225, 623423, 6645345])
  .exec(function (err, records) {
    //make magic happen
  });

I find the dot notation quite handy for querying into sub documents.

http://mongoosejs.com/docs/queries.html


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon