'How to get diff between tow queries in mongodb?
I have collection
[{
"_id" : "5c9a69ef42c82b0197a2ffb8",
"key" : "a",
"language" : "en",
"version" : "0.1",
},
{
"_id" : "5c9a69ef42c82b0197a2ffb8",
"key" : "b",
"language" : "en",
"version" : "0.1",
},
{
"_id" : "5c9a69ef42c82b0197a2ffb8",
"key" : "b",
"language" : "en",
"version" : "0.2",
},
{
"_id" : "5c9a69ef42c82b0197a2ffb8",
"key" : "c",
"language" : "en",
"version" : "0.2",
}]
so I have 2 queries that getting version 0.1 and version 0.2, And I need to find the difference between them?
I need to get all of translation 0.2 that does not exist in translation 0.1.
Solution 1:[1]
Here is a solution to get all translations key that has a 0.2 version but not a 0.1 version.
- First I
$sortthe translations by versions. - Then with
$group, I get all the versions for a givenkey. $matchremove all the key that have a version 0.1$replaceRootkeep only the last version for akey
db.collection.aggregate([
{
"$sort": {
"version": 1
}
},
{
$group: {
"_id": "$key",
"items": {
"$push": "$$ROOT"
}
}
},
{
"$match": {
"items.version": {
"$ne": "0.1"
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$last": "$items"
}
}
}
])
try it here
If you remove the $match, you can also retrieve the last version available for each translation.
- key a => version 0.1
- key b => version 0.2
- key c => version 0.2
db.collection.aggregate([
{
"$sort": {
"version": 1
}
},
{
"$group": {
"_id": "$key",
"items": {
"$push": "$$ROOT"
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$last": "$items"
}
}
}
])
try it here
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 | AlexisG |
