Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - find() with multiple ids that are the same

If I were to perform this query with mongoose;

Schema.find({
    _id: {
        $in: ['abcd1234', 'abcd1234', 'abcd1234']
    }
});

The query will only return something like:

[{
    'property1': 'key1',
    'property2': 'key2'
}]

With the array only having one object, obviously because I passed in all the same id's. However, I actually want duplicate objects returned. How can I do this?

like image 652
Alex Wohlbruck Avatar asked Dec 05 '25 19:12

Alex Wohlbruck


1 Answers

Mongo itself will only return objects with no duplicates. But you can then build an array of objects with duplicates from that.

For example, if array is the array of objects returned my Mongo - in this case:

var array = [{
    _id: 'abcd1234',
    property1: 'key1',
    property2: 'key2'
}];

and ids is your list of IDs that you want with duplicates - in your case:

var ids = ['abcd1234', 'abcd1234', 'abcd1234'];

then you can do:

var objects = {};
array.forEach(o => objects[o._id] = o);
var dupArray = ids.map(id => objects[id]);

Now dupArray should contain the objects with duplicates.

Full example:

var ids = ['abcd1234', 'abcd1234', 'abcd1234'];
Schema.find({_id: {$in: ids}}, function (err, array) {
  if (err) {
    // handle error
  } else {
    var objects = {};
    array.forEach(o => objects[o._id] = o);
    var dupArray = ids.map(id => objects[id]);
    // here you have objects with duplicates in dupArray:
    console.log(dupArray);
  }
});
like image 70
rsp Avatar answered Dec 08 '25 09:12

rsp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!