Thursday, 1 June 2017

How to query multiple documents in MongoDB with duplicates?

Usually I search for multiple queries by using $in:

For example, suppose I have the following collection:

{ name: 'Bob', age: 21, creditcard: 123456789 }
{ name: 'An', age: 22, creditcard: 234567891 }
{ name: 'John', age: 18, creditcard: 345678912 }
{ name: 'Joe', age: 19, creditcard: 456789123 }

If Bob and An bought a beer then I retrieve their age and credit card by making the following query:

let query = {
    name: {
        $in: ['Bob', 'An']
    }
};

and using it here:

db.persons.find(query).toArray((err, result) => { console.log(result) });

This gives us:

[{ name: 'Bob', age: 21, creditcard: 123456789 },
{ name: 'An', age: 22, creditcard: 234567891 }]

But suppose that Bob bought two beers, then my query is:

let query = {
    name: {
        $in: ['Bob', 'Bob']
    }
};

Doing the same trick gives us a result that will contain the information of Bob only one time.

{ name: 'Bob', age: 21, creditcard: 123456789 }

It is normal since I am using $in.

But how should I do in order to get the information multiple times so that I have this result:

[{ name: 'Bob', age: 21, creditcard: 123456789 },
{ name: 'Bob', age: 21, creditcard: 123456789 }]

Right now I am writing JavaScript to fix that issue. But I'm wondering if MongoDB can do it so I can remove some code.



via dll

No comments:

Post a Comment