سؤال

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....
هل كانت مفيدة؟

المحلول

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 );

نصائح أخرى

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

User.where({ records: { $in: [3225, 623423, 6645345] } }, function ...

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

For me, work this way

IDs=["5b00c4b56c7fb80918293dd9","5b00c4b56c7fb80918293dd7",...]
const users= await User.find({records:IDs}) 

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();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top