简体   繁体   中英

Modify the query to get the expected result

I am trying to modify query to get expected output.I am able to write the query but not getting the output as expected so that I may bind in the front end.

Actual output:-

{
    "_id" : null,
    "first" : 3571.0,
    "second" : 24.0
}

Expected output:-

{    "_id" : null,
    "opertion":edit,
    "count" : 3571.0,
}
{    "_id" : null,
    "opertion":read,
    "count" : 24,
}
{    "_id" : null,
    "opertion":update,
    "count" : 9000,
}

Myquery:-

db.getCollection('blog').aggregate([
  { "$group": {
    "_id": null,
    "first": {
      "$sum": {
        "$cond": [{ "$in": ["$Operation", ["edit1", "edit2"]] }, 1, 0]
      }
    },
    "second": {
      "$sum": {
        "$cond": [{ "$in": ["$Operation", ["read1", "read2"]] }, 1, 0]
      }
    }
  },
},

])

if you have collection which is like as below:

[
{
    "_id" : 1,
    "operation" : "edit1" # some extra fields 
},
{
    "_id" : 2,
    "operation" : "read1"
},
{
    "_id" : 3,
    "operation" : "update1"
}
]

by using $project and $cond you can rename the "read1", "read2" to read or updates to update , or edits to edit then by grouping on the new operation field you can get the count of each operation. you can use this query:


db.aggregate([
    {
        "$project": {
            "new_operation":
            {
                "$cond": [
                    {"$in":
                         ["$Operation", ["edit1", "edit2"]]
                    }, "edit", {
                        "$cond": [
                            {"$in":
                                 ["$operation", ["read1", "read2"]]
                            }, "read", "update"]
                    }
                ]
            }
        }
    },
    {
        "$group": {
            "_id": "$new_operation",
            "count": {"$sum": 1}
        }
    }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM