Push operation in mongo

Write a Mongo Pipeline query for the push operation.

Example:

[{ 
    "_id" : ObjectId("6020d98f62864f47ec0e1ca3"), 
    "mediaSite" : "facebook", 
    "date" : ISODate("2021-02-05T18:30:00.000+0000"), 
    "hourly_View" : {
        "1" : 123.0, 
        "2" : 323.0, 
        "3" : null, 
        "4" : 262.0, 
        "5" : null, 
        "6" : 526.0, 
        "7" : 232.0, 
        "8" : null, 
        "9" : 654.0, 
        "10" : null, 
        "11" : 123.0, 
        "12" : 0.0, 
        "13" : 234.0, 
        "14" : 262.0, 
        "15" : 872.0, 
        "16" : 526.0, 
        "17" : 232.0, 
        "18" : 635.0, 
        "19" : 654.0, 
        "20" : 765.0, 
        "21" : 765.0, 
        "22" : -123.0, 
        "23" : 323.0, 
        "24" : 234.0
    }
}
]

Approach

Query: push operation in mongo and filtration of null and negative value.

 
db.getCollection("SocialMediaTik").aggregate([
    {$match:{"mediaSite":"facebook"}},
    {$project:{"mediaSite":1,"view":{$objectToArray:"$hourly_View"}}},
    {$unwind:"$view"},
    {$match:{"view.v":{$gt:0,$ne:null}}},
    {$group:{"_id":"mediaSite","hourly_View":{$push:{"key":"$view.k","value":"$view.v"}}}}
    ]);

Output: 

[
 { 
    "_id" : "mediaSite", 
    "hourly_View" : [
        {
            "key" : "1", 
            "value" : 123.0
        }, 
        {
            "key" : "2", 
            "value" : 323.0
        }, 
        {
            "key" : "4", 
            "value" : 262.0
        }, 
        {
            "key" : "6", 
            "value" : 526.0
        }, 
        {
            "key" : "7", 
            "value" : 232.0
        }, 
        {
            "key" : "9", 
            "value" : 654.0
        }, 
        {
            "key" : "11", 
            "value" : 123.0
        }, 
        {
            "key" : "13", 
            "value" : 234.0
        }, 
        {
            "key" : "14", 
            "value" : 262.0
        }, 
        {
            "key" : "15", 
            "value" : 872.0
        }, 
        {
            "key" : "16", 
            "value" : 526.0
        }, 
        {
            "key" : "17", 
            "value" : 232.0
        }, 
        {
            "key" : "18", 
            "value" : 635.0
        }, 
        {
            "key" : "19", 
            "value" : 654.0
        }, 
        {
            "key" : "20", 
            "value" : 765.0
        }, 
        {
            "key" : "21", 
            "value" : 765.0
        }, 
        {
            "key" : "23", 
            "value" : 323.0
        }, 
        {
            "key" : "24", 
            "value" : 234.0
        }
    ]
}
  
]


No comments:

Post a Comment