Mongodb - Use . distinct in 2 properties of a document

Asked

Viewed 29 times

0

I have the following data set 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 in color. The result should be like this:

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

I tried to use the function distinc.

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

But it only supports one property

Using the function Aggregate I can’t distinguish the properties.

Something like:

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

Does not distinguish the items by format or color nor group them in the same JSON. Someone can help me?

1 answer

1


I think the method $unwind 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'
        }
    }},
])
  • That worked perfectly. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.