Home > other >  How to get the document inside a field out after "group by" in MongoDB?
How to get the document inside a field out after "group by" in MongoDB?

Time:02-04

The documents I work are like this:

{
    "id" : 98syf87erfw8n
    "foo" : { "objectid" : "39", "stuff" : "65" },
    "yearpublished" : "1979",
    .
    .
    .
}

This is the query I used:

db.foobar.aggregate([
    { $group : {
        _id : '$yearpublished',
        myItem: { $first: "$$ROOT" }
    }}
])

The final output is in the form:

{
    { "_id" : "1923", "myItem" : {
                            "id" : 98syf87erfw8n,
                            "foo" : { "objectid" : "39", "stuff" : "65" },
                            "yearpublished" : "1979"
                        }
    }, 
    { "_id" : "1453", "myItem" : {
                            "id" : 88888888888,
                            "foo" : { "objectid" : "394", "stuff" : "55" },
                            "yearpublished" : "1453"
                            "author" : "Ravi Kiran"
                        }
    }
};

But I want the output as:

{
    "id" : "98syf87erfw8n",
    "foo" : { "objectid" : "39", "stuff" : "65" },
    "yearpublished" : "1979"
},
{
    "id" : "88888888888",
    "foo" : { "objectid" : "394", "stuff" : "55" },
    "yearpublished" : "1453",
    "author" : "Ravi Kiran"
}

This means I want to get those documents inside the field myItem out. How can I do that?

CodePudding user response:

You could use $replaceRoot

Play

db.collection.aggregate({
  "$replaceRoot": {
    "newRoot": "$myItem"
  }
})

There are syntax errors in your output.

"id" : 98syf87erfw8n, is invalid.

It should be "id" : "98syf87erfw8n", Note the quotes

There is comma missing after yearPublished in the second object.

CodePudding user response:

One more project stage after the $group can do the job:

{
 $project: {
  yearpublished: "$myItem.yearpublished",
  foo: "$myItem.foo",
  id: "$myItem.id",
  _id: 0
 }
}

playground

  •  Tags:  
  • Related