Reputation: 2894
Given the following schema, I'm trying to find all distinct sub-document (item) for a condition.
{
"basket": "one",
"color":"brown",
"items": [
{
"id":123,
"name": "apple"
},
{
"id":234,
"name": "banana"
},
]
},
{
"basket": "2",
"color":"brown",
"items": [
{
"id":345,
"name": "orange"
},
{
"id":123,
"name": "apple"
},
]
},
{
"basket": "3",
"color":"blue",
"items": [
{
"id":345,
"name": "orange"
},
{
"id":456,
"name": "pineapple"
},
]
}
Is there a way in mongodb to get all distinct items where the basket color is "brown"?
Ideally, result should be:
{
"id":123,
"name": "apple"
},
{
"id":234,
"name": "banana"
},
{
"id":345,
"name":"orange"
}
Upvotes: 0
Views: 232
Reputation: 155
After that you can run following-
In case of "items" sub-document
db.Collection_Name.distinct("items",{"color": "brown"})
Upvotes: 1
Reputation: 36
Official doc here: https://docs.mongodb.com/v3.2/reference/method/db.collection.distinct/#db.collection.distinct
db.collection.distinct(field,query)
where:
field - The field for which to return distinct values (string).
query - A query that specifies the documents from which to retrieve the distinct values (document).
So in your case:
db.collection.distinct("items",{"color":"brown"})
Upvotes: 2