Question about group query with sub-documents...

31 views
Skip to first unread message

Steve Gaylord

unread,
Sep 28, 2016, 5:03:04 PM9/28/16
to mongodb-user
I have just upgraded my database from 2.4 to 3.2.8 and I have found a grouping issue where records are not grouped that have matching data.  We are running with mongoose on compose for hosting.

The issue comes up when I am grouping on a sub-document and all elements in that sub-document.  It looks like when the upgrade was complete the ordering of some of the elements changed and that seems to be impacting the group.

It feels like the grouping is taking the entire sub-document as a string and grouping on that string and not looking at it element by element.

For example with the three documents below when I do a group like the below I get three records instead of on.

Group statement:
{$group: {
    _id: {
             _id: '$person._id',
             name: '$person.name',
             address: $person.address'
           }
}


Document 1:
{
_id: 1234,
name: "my name",
address: {
street: "123 my street",
city : "my city",
state: "state"
}
}

Document 2:
{
_id: 1234,
name: "my name",
address: {
city : "my city",
street: "123 my street",
state: "state"
}
}

Document 3:
{
_id: 1234,
name: "my name",
address: {
state: "state"
city : "my city",
street: "123 my street",
}
}

Kevin Adistambha

unread,
Oct 13, 2016, 1:01:46 AM10/13/16
to mongodb-user
Hi,

>I have just upgraded my database from 2.4 to 3.2.8 and I have found a grouping issue where records are not grouped that have matching data.  We are running with mongoose on compose for hosting.

>The issue comes up when I am grouping on a sub-document and all elements in that sub-document.  It looks like when the upgrade was complete the ordering of some of the elements changed and that seems to be impacting the group.

>It feels like the grouping is taking the entire sub-document as a string and grouping on that string and not looking at it element by element.

In MongoDB, the field ordering has always been significant. For example, documents `{a:1, b:1}` and `{b:1, a:1}` are considered two different documents. Consequently, field ordering in sub-documents are also significant.

If you need to perform a `$group` on a sub-document, it's best to specify individual fields instead of the whole sub-document. For example:

```json
{$group: {
    _id: {
        _id: '$person._id',
        name: '$person.name',
        address: {
            street: '$person.address.street',
            city: '$person.address.city',
            state: '$person.address.state'
        }
    }
}
```

Please note that the latest MongoDB version is currently 3.2.10. I would recommend you to upgrade for bugfixes and improvements.

Best regards,
Kevin
Reply all
Reply to author
Forward
0 new messages