I am trying this mongodb aggregation. I got the output but how can I get the count value with all records.
db.STREETLIGHTS.aggregate(
[
{$match : {"CreateDate":{$gt:new Date(ISODate("2018-04-09T23:54:16.064Z") - 24*60*60 * 1000)}}},
{ $project: {_id:1, SLC_ID:1,LONGITUDE:1,LATITUDE:1,DCUID:1,CUMILITIVE_KWH:1,LAMPSTATUS:1,CreateDate:1 } },
]
)
Please try this.
db.STREETLIGHTS.aggregate([
{$match : {"CreateDate":{$gt:new Date(ISODate("2018-04-09T23:54:16.064Z") - 24*60*60 * 1000)}}},
{$project: {_id:1, SLC_ID:1,LONGITUDE:1,LATITUDE:1,DCUID:1,CUMILITIVE_KWH:1,LAMPSTATUS:1,CreateDate:1 } },
{$group: {_id: null, count: {$sum: 1}}}
])
You need to use the $sum operator in the $project stage :
{$project: {
// Your others projections
total: {$sum: 1}
}
Related
I'm trying to get the average of a puntations for some stores weekly in Mongo but it don't work. Could u help me?
db.collection.aggregate(
[
{$match:{storeId:{$in:[
ObjectId("e069d1b76557685b9e235v"),ObjectId("e069d1b76557685b9t7j8n"),
ObjectId("e069d1b76557685b9e2fg6"),ObjectId("e069d1b76557685b9p56r2")
]}}},
{$group:{_id:"$storeId", week: { date: new Date("$createdAt") }, totalPoints: {$sum: "$points"}, averagePoints: {$avg: "$points"}} },
{$sort: {totalPoints:-1}}
])
It doesn't work. But if I delete the part of the week, the code work it but make a wrong average
db.collection.aggregate(
[
{$match:{storeId:{$in:[
ObjectId("e069d1b76557685b9e235v"),ObjectId("e069d1b76557685b9t7j8n"),
ObjectId("e069d1b76557685b9e2fg6"),ObjectId("e069d1b76557685b9p56r2")
]}}},
{$group:{_id:"$storeId", totalPoints: {$sum: "$points"}, averagePoints: {$avg: "$points"}} },
{$sort: {totalPoints:-1}}
])
For groupBy week you can use $week function from mongo and add start Date in $match operation.
db.collection.aggregate(
[
{$match:{storeId:{$in:[
ObjectId("e069d1b76557685b9e235v"),ObjectId("e069d1b76557685b9t7j8n"),
ObjectId("e069d1b76557685b9e2fg6"),ObjectId("e069d1b76557685b9p56r2")
]},
timeStamp: {$gt: ISODate(createdAt)},
}},
{$group:{_id:"$storeId", week: { $week: '$timeStamp'}, totalPoints: {$sum: "$points"}, averagePoints: {$avg: "$points"}} },
{$sort: {totalPoints:-1}}
])
All my document in my database (data) have a tags_data :
tags_data : [ "am", "gi", "bab", "as", "bru", "dan", "tea", "wec", "fuy" ]
So i would like to sort a recap of all tags with the number of occurence for each tag and if possible sort them in an descending sort
I'am trying to do it like this :
db.data.aggregate(
{$unwind: '$tags_data'},
{$group: {_id: '$tags_data', sum: {$sum: +1}}}
);
Thanks and regards
The answer was :
db.data.aggregate(
{$unwind: '$tags_data'},
{$group: {_id: '$tags_data', sum: {$sum: +1}} },
{$sort: {sum: -1}}
);
thanks
I'm new to Mongodb aggregate(). When I was trying it from Mongo shell, it worked fine like the following code:
> db.trics.aggregate( [ {$group: {_id: "$club", count: {$sum: 1}}}, {$sort: {count: -1}}, {$limit: 1} ] )
{ "_id" : 0, "count" : 2 }
But, when I moved the same aggregation operation to my server backed by Mongoose,
Object.aggregate([ {$group: {_id: "$club", count: {$sum: 1}}} ]).sort('-count').limit(1)
the "_id" of the $group result was always returning "null": What I got from postman
[ { _id: null, count: 2 } ]
Could any Mongo/Mongoose expert help me out of this please?
Many thanks
FYI: the "Object" document example:
{
"_id" : 0, // auto increment primary key for "Object" collection
club" : 0, // auto increment primary key for "Club" collection
}
Say I have the following:
this.aggregate(
{$unwind: "$tags"},
{$match: {tags: {$in: pip.activity.tags}}},
{$group : {_id : '$_id',matches:{$sum:1}}},
{$project: { _id: 0,matches:1}},
{$sort: {matches:-1 }},
callback
);
how would I go about including an additional 'external' objectId field in the results? e.g if I have the following:
var otherField = new ObjectId('xxxxxxx');
this.aggregate(
{$unwind: "$tags"},
{$match: {tags: {$in: pip.activity.tags}}},
{$group : {_id : '$_id',matches:{$sum:1}}},
{$project: { _id: 0,matches:1,otherField:otherField}}, <-- include otherField
{$sort: {matches:-1 }},
callback
);
Is this possible or should I be using a forLoop or MapReduce for this particular step? I'm looking for something really efficient.
The $project pipeline operator would not let you inject the object, but you can probably insert the object id earlier in the $group operator. If you have a collection:
db.foo.save({_id:1,tags:['a','b']})
db.foo.save({_id:2,tags:['b','c']})
db.foo.save({_id:3,tags:['c','d']})
You can then write:
db.foo.aggregate({
$unwind: "$tags"},{
$match: { tags: {$in: ['b','c'] } }},{
$group: { _id: "$_id", matches: {$sum: 1 }, otherField: {$min: new ObjectId()} }},{
$project: { _id: 0, matches: 1, otherField: 1 }},{
$sort: { matches: -1 }})
The $min or $max can be used here, but it expects an operator or reference to a field so you have to give it one..
After piping various documents through the aggregate framework I finally have the resultant documents.
The problem now is that I only want the $first and $last document.
The final document looks like this (huge list):
...
{
"_id" : "Kaila Deibler",
"count" : 406
},
{
"_id" : "Jessika Dagenais",
"count" : 406
},
{
"_id" : "Tamika Schildgen",
"count" : 404
},
...
The mongo shell command that I used to produce the document is:
db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}])
But I only need the first and last document so I attempted something like this:
db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}, {$first: "$_id"}])
I tried other implementations but can't seem to figure out when/where to implement $first and $last
Any suggestions?
$first and $last are aggregation functions in the $group pipeline, which means you need to use them inside the $group document.
db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}, first: {$first:"$_id"}}}, {$sort: {count: -1}}])
Similarly for $last
You can find an example that shows this here
Here is my own answer to this question:
db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}, {$group: {_id: "$_id.comments.author", first: {$first: "$_id"}, last: {$last: "_id"}}}])
Since I want to pull the first and last document after the sort I have to apply another $group with $first and $last. The result:
{
"result" : [
{
"_id" : null,
"first" : "Elizabet Kleine",
"last" : "Mariela Sherer"
}
],
"ok" : 1
}
Note the "_id" : null. Is this necessary?
If anyone has a better solution please share.