MongoDB Aggregation 02


db.Persons.aggregate([
{$project: {isActive: 1, name:1, gender:1}}
])
//OUTPUT : 
{
    "_id" : ObjectId("5f1f23e002c633f9f578dcde"),
    "name" : "Aurelia Gonzales",
    "isActive" : false,
    "gender" : "female"
}

db.Persons.aggregate([
{$project: {
    _id:0,
    index: 1,
    name: 1,
     info: {
         eyes: "$eyeColor",
         company: "$company.title",
         country: "$company.location.country"
         }
    }}
])
//OUTPUT :
{
    "index" : 1,
    "name" : "Kitty Snow",
    "info" : {
        "eyes" : "blue",
        "company" : "DIGITALUS",
        "country" : "Italy"
    }
}


Arrays $group issue

db.Persons.aggregate([
//stage 1
{$group: {_id: "$tags"}}
])
//OUTPUT :
{
    "_id" : [ 
        "ipsum", 
        "nisi", 
        "deserunt"
    ]
}
/* 2 */
{
    "_id" : [ 
        "proident", 
        "laborum", 
        "sint"
    ]
}

Above output is not expected one, we need to group by value of an array.

db.Persons.aggregate([
//stage 1
{$unwind: "$tags"},
//stage 2
{$project: {name: 1, index: 1, tags: 1}}
])
//OUTPUT :
/* 1 */
{
    "_id" : ObjectId("5f1f23e002c633f9f578dcde"),
    "index" : 0,
    "name" : "Aurelia Gonzales",
    "tags" : "enim"
}

/* 2 */
{
    "_id" : ObjectId("5f1f23e002c633f9f578dcde"),
    "index" : 0,
    "name" : "Aurelia Gonzales",
    "tags" : "id"
}

/* 3 */
{
    "_id" : ObjectId("5f1f23e002c633f9f578dcde"),
    "index" : 0,
    "name" : "Aurelia Gonzales",
    "tags" : "velit"
}

$unwind and $group

db.Persons.aggregate([
//stage 1
{$unwind: "$tags"},
//stage 2
{$group: {_id: "$tags"}}
])
//OUTPUT : 
/* 1 */
{
    "_id" : "et"
}

/* 2 */
{
    "_id" : "elit"
}

/* 3 */
{
    "_id" : "fugiat"
}

Leave a Reply

Your email address will not be published. Required fields are marked *