'MongoDB: Filter documents by multiple aspects sharing same value
I have a collection like this
{
"productId" : ObjectId("someId-1"),
"value" : "Nike",
"key" : "Brand",
},
{
"productId" : ObjectId("someId-1"),
"value" : "Blue",
"key" : "Color",
},
{
"productId" : ObjectId("someId-2"),
"value" : "Nike",
"key" : "Brand",
},
{
"productId" : ObjectId("someId-2"),
"value" : "Red",
"key" : "Color",
},
and I want to make a query to get all product Ids that share these aspects
[
{
key: "Brand",
value: "Nike",
},
{
key: "Color",
value: "Blue",
},
]
And this should return productId = someId-1
Note that I want to make use of indexes created on all three fields(productId, key, value)
Solution 1:[1]
You should use $lookup
db.collection.aggregate([
{ "$match": { "key": 'Brand', 'value':'Nike' }},
{ "$lookup": {
"from": "collection",
"localField": "productId",
"foreignField": "productId",
"as": "ids"
}}
])
It will do a simple join in the same collection.
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 | Gibbs |
