'How to retrieve the unique records from mongodb
I am facing a bit of difficulty in the writing a mongodb query actually, tried various queries but one seems to be working out.
I have a db of records of the similar one, i need to retrieve a the documents based on priority.
Records
[
{name :"abc", age:"45",gender:"male", interests :"sports"},
{name :"xyz", age:"60",gender:"male", interests :"books"}
{name :"abc", age:"45",gender:"male" interests :"books"},
{name :"qwerty", age:"15",gender:"female" interests :"sports"}
]
Expected Output
[
{name :"abc", age:"45", interests :"sports"},
{name :"xyz", age:"60", interests :"books"}
]
the output of db query should be based on priority
Explanation: I need to retrive the records of gender male, and when looking for interests if a user has interest on sports, we should ignore the record of books for that user, but if a user doesn't have a record on sports, we need to return the record matching books.
I wrote a aggregation query, but not fitting my expectation so looking for alternatives.
Solution 1:[1]
Let me Help you with a suggestion -
[{$match: {
gender: "male",
}}, {$group: {
_id: "$name",
age: {$first: "$age"},
gender: {$first: "$gender"},
interests: {$push: "$interests"},
}}, {$project: {
name: "$name",
age: "$age",
gender: "$gender",
interests: {
$cond: {
if: {"$in": ["sports", "$interests"]},
then: "sports",
else: "books"
}
}
}}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sourbh Gupta |
