1

Suppose I have inventory data as follows:

[
  {"_id":"0001","name":"test_001","value":"abc"},
  {"_id":"0002","name":"test_001","value":"abc"},
  {"_id":"0003","name":"test_001","value":"xyz"},
  {"_id":"0004","name":"test_003","value":"abc"}
]

Now I want result to be something like this:

{
  "gouped": {
    "test_001": ["abc", "xyz"],
    "test_002": ["abc"]
  }
}

I tried something like this using $lookup

db.inventory.aggregate([
  {
    $lookup:
      {
        from: "inventory",
        let: { name: "$name", value: "$value" },
        pipeline: [
          { $match:
              { $expr:

                { $eq: [ "$name",  "$$name" ] }

              }
          },
          { $project: { grouped: 1, name: 1, value: 1 } }
        ],
        as: "grouped"

      }
  },
  { $project : {   grouped : 1 } }
])

This gave me result something like this:

{ "_id" : "001", "grouped" : [ 
{ "_id" : "001", "name" : "test_001", "value" : "abc" }, 
{ "_id" : "002", "name" : "test_001", "value" : "abc" }, 
{ "_id" : "003", "name" : "test_001", "value" : "xyz" }] }

I guess it will be fine even if I get in the above format with unique value. I can then achieve final result using javascript.

Freddy
  • 2,216
  • 3
  • 31
  • 34
  • You can use $group stage. Something like `db.inventory.aggregate({$group:{_id:"$name", values:{$push:"$value"}}})` – s7vr Jan 03 '19 at 20:06
  • @Veeram `$addToSet` instead `$push` did the trick. Maybe you can add it as an answer? – Freddy Jan 03 '19 at 20:14

0 Answers0