简体   繁体   中英

NodeJS with MongoDB - Get Nested Collection matching one of an array objects

I am trying to write a query in NodeJS and just having troubles with the syntax.

I am new to Mongo and i have a though time with some complex(for my level at least) query.

I have an array of mongo Ids (lets call it mongoArr). I have a collection called data. Within this data collection there is a nested object called innerNested. I am trying to retrieve is all of the "data" elements that their "innerNested" id is equal to one of the ids in my array

if it was a simple JS it would have been:

var output = [];
for (var i=0;i<data.length;i++)
{
   if (mongoArr.indexOf(data[i].innerNested.$id) != -1)
  {
     output.push(data[i];
  }
}

If you're using Mongoose, you can reference fields of "innerNested" directly in your query like this

Person.find({
    'innerNested._id': {
         $in: mongoArr
    }
}, function(err, docs) {
    console.log(docs);
});

where the "$in" clause will check if the ID is within your array of IDs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM