Home > Net >  How can I group documents by object in mongodb aggregation?
How can I group documents by object in mongodb aggregation?

Time:10-26

I was grouping documents based on object, it works perfect but I have no idea whether mongo group (object) based on reference or value. I mean, mongo works on reference based or values based while we group.

Anybody knows, what's the behind the hook working of $group? Is mongo group based on reference or value?

Here are dummy documents,

[
  {
    name: "a",
    title: {
      title: "b",
      order: 1
    },
    group: "B"
  },
  {
    name: "b",
    title: {
      title: "b",
      order: 1
    },
    group: "Bs"
  },
  {
    name: "c",
    title: {
      title: "c",
      order: 2
    },
    group: "B"
  }
]

aggregation query,

db.collection.aggregate([
  {
    "$group": {
      "_id": "$title",
      "items": {
        "$addToSet": {
          "name": "$name",
          "group": "$group"
        }
      }
    }
  }
])

it returns,

[
  {
    "_id": {
      "order": 1,
      "title": "b"
    },
    "items": [
      {
        "group": "B",
        "name": "a"
      },
      {
        "group": "Bs",
        "name": "b"
      }
    ]
  },
  {
    "_id": {
      "order": 2,
      "title": "c"
    },
    "items": [
      {
        "group": "B",
        "name": "c"
      }
    ]
  }
]

CodePudding user response:

MongoDB uses this comparison rules

See how it compares objects, it goes field by field, checks name and then value etc. It goes inside and its recursive.

  • Related