MongoDB - Use .distinct on 2 properties of a document

0

I have the following dataset in my database:

{ "_id": 1, "dept": "A", "item": { "format": "circle", "color": "red" }}
{ "_id": 2, "dept": "A", "item": { "format": "circle", "color": "blue" }}
{ "_id": 3, "dept": "B", "item": { "format": "rect", "color": "green" }}
{ "_id": 4, "dept": "A", "item": { "format": "rect", "color": "geen" }}
{ "_id": 5, "dept": "B", "item": { "format": "circle", "color": "blue" }}
{ "_id": 6, "dept": "A", "item": { "format": "rect", "color": "blue" }}
{ "_id": 7, "dept": "B", "item": { "format": "circle", "color": "blue" }}

I need to distinguish them based on format and color . The result should look like this:

{"format" : "circle", color : "red"}
{"format" : "circle", color : "blue"}
{"format" : "rect", color : "green"}
{"format" : "rect", color : "blue"}

I tried to use the distinc function.

db.collection.distinct('item.format')

But it only supports a property

Using the aggregate function I can not distinguish properties.

Something like:

db.getCollection().aggregate([
    { $group : { 
        _id : {
            format: '$item.format',
            color : '$item.color'
        }
    }},
])

Do not distinguish items by format or color nor group them into a same JSON. Can anyone help me?

    
asked by anonymous 30.10.2018 / 19:46

1 answer

1

I think the $ unwind method would solve your situation.

It would first separate the items from the item and then you would give the aggregate group .

db.getCollection().aggregate([
    { $unwind: '$item'},
    { $group : { 
        _id : {
            format: '$item.format',
            color : '$item.color'
        }
    }},
])
    
31.10.2018 / 20:47