0

I am trying to query multiple documents based on an array of document IDs.

Here is an example array: [{_id: '123151djadjw11', quantity: 1}, {_id: 'some4idda123131', quantity: 2}];

I want to be able to send an array like that to the server and retrieve the documents matching the ID property in each of the objects in the array.

Any ideas would be greatly appreciated! Thanks in advance!

  • get all ids from array to one array value like `let ids = ['123151djadjw11', 'some4idda123131']` and for filter use [$in](https://docs.mongodb.com/manual/reference/operator/query/in/) like this `{_id: {$in: ids}}`. – turivishal Jul 28 '20 at 09:39
  • Look [here](https://stackoverflow.com/questions/5818303/how-do-i-perform-an-id-array-query-in-mongoose/5822327) – Getter Jetter Jul 28 '20 at 09:39

1 Answers1

0
let array1 = [{_id: '123151djadjw11', quantity: 1}, {_id: 'some4idda123131', quantity: 2}];
let array2 = array1.map(a => a._id);

//results array2 =['123151djadjw11', 'some4idda123131'];

db contains values as { "_id" : "123151djadjw11", "quantity" : 1.0 } { "_id" : "some4idda123131", "quantity" : 2.0 } { "_id" : "3rdId", "quantity" : 5.0 }

let array3 = db.objects.find({_id:{$in : array2}}).toArray();

//returns array3= [{_id: '123151djadjw11', quantity: 1}, {_id: 'some4idda123131', quantity: 2}]

Selva Mary
  • 658
  • 1
  • 4
  • 17