42

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....
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

5 Answers5

85

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

kberg
  • 2,059
  • 1
  • 19
  • 11
46

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 );
Tomke
  • 38
  • 1
  • 9
neebz
  • 11,465
  • 7
  • 47
  • 64
  • 4
    But what's the syntax in mongoose? – TIMEX Apr 28 '11 at 19:51
  • 2
    it's the same syntax. `.find()` is a mongodb function. – neebz Apr 28 '11 at 20:01
  • Thanksk. What if my "id" is actually nested. The object is: { fb: { name:blah, id:blah } } . How would I query it by that id? Can you write it out for me? tanks. – TIMEX Apr 28 '11 at 20:09
  • 6
    `Users.find( { "fb" : { id: { $in : arrayOfIds } } } );` I haven't tested it but it should work – neebz Apr 28 '11 at 20:15
  • this is ridiculous, what if you're progressively building a query based on HTTP parameters and you have to check to see if they exist before you build the query?? like this `var query = Users.find(); if (x) { query.in(x) //?! }` ? will that work? –  Jul 23 '14 at 15:07
  • 2
    What's up with the "fb"? This didn't work for me, but this did: `Users.find({_id: {$in:arrayOfIds} })` – ki9 Mar 15 '18 at 01:09
8
User.where({ records: { $in: [3225, 623423, 6645345] } }, function ...

more info here: http://docs.mongodb.org/manual/reference/operator/query/

Sagiv Ofek
  • 25,190
  • 8
  • 60
  • 55
0

For me, work this way

IDs=["5b00c4b56c7fb80918293dd9","5b00c4b56c7fb80918293dd7",...]
const users= await User.find({records:IDs}) 
Alex Montoya
  • 4,697
  • 1
  • 30
  • 31
0

Ids is the array of object ids:

const ids =  [
    '4ed3ede8844f0f351100000c',
    '4ed3f117a844e0471100000d', 
    '4ed3f18132f50c491100000e',
];

With callback:

User.find().where('_id').in(ids).exec(callback);

With async function:

records = await User.find().where('_id').in(ids).exec();
snnsnn
  • 10,486
  • 4
  • 39
  • 44