Skip to content

Instantly share code, notes, and snippets.

@omeroot
Last active April 16, 2016 15:53
Show Gist options
  • Select an option

  • Save omeroot/a623446eb64e187d7f61 to your computer and use it in GitHub Desktop.

Select an option

Save omeroot/a623446eb64e187d7f61 to your computer and use it in GitHub Desktop.
# ##### ##### ###### ####### ##### # ####### ####### #
# # # # # # # # # # # # # # # ##
# # # # # # # # # # # # # #
# # # #### # #### ###### ##### # #### # # # ##### #
####### # # # # # # # # # ####### # # #
# # # # # # # # # # # # # # # #
# # ##### ##### # # ####### ##### # # # ####### #####
//example object of document
{
"_id": "10280",
"city": "NEW YORK",
"state": "NY",
"pop": 5574,
"loc": [
-74.016323,
40.710537
]
}
//above query is returns the smallest and largest cities by population for each state
aggregate([
{
{
$group:{
_id: {state: '$state', city: '$city'},
pop: {$sum: '$pop'}
},
},
{$sort: {pop: 1}},
{
$group: {
_id: '$_id.state',
biggestCity: {$last: '$_id.city'},
biggestPop: {$last: '$pop'},
smallestCity: {$first: '$_id.city'},
smallestPop: {$first: '$pop'}
}
},
{
$project: {
_id: 0,
state: '$_id',
biggestCity: {name: '$biggestCity', pop: '$biggestPop'},
smallestCity: {name: '$smallestCity', pop: '$smallestPop'}
}
}
}
]);
# ##### ##### ###### ####### ##### # ####### ####### #####
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # #
# # # #### # #### ###### ##### # #### # # # ##### #####
####### # # # # # # # # # ####### # # #
# # # # # # # # # # # # # # # #
# # ##### ##### # # ####### ##### # # # ####### #######
//example object of document
//in accessPassHistory Array, objects has readerGroup and type (0 is out, 1 is in)
{
"_id" : ObjectId("570cb14a95aa4a70229fed81"),
"accessPassHistory" : [
{
"_id" : ObjectId("570cd5ce2134d7e41be0249a"),
"type" : "0",
"date" : ISODate("2016-04-12T11:02:38.689+0000"),
"readerGroup" : "570a639c1ffb50b8086f4bc1",
"reader" : "06011615"
},
{
"_id" : ObjectId("570cd5d72134d7e41be0249c"),
"type" : "1",
"date" : ISODate("2016-04-12T11:02:47.300+0000"),
"readerGroup" : "570a639c1ffb50b8086f4bc1",
"reader" : "06011614"
}
]
}
//above query is returns, that is if last type in matched readerGroup is current type access is denied else entered
/**
* @param {string} readerGroup
* @param {string} cardId
*/
Card.aggregate([
{"$match": {cardId: cardId}},
{"$project": {access: "$accessPassHistory"}},
{$unwind: "$access"},
{$group: {_id: "$access.readerGroup", lastAccess: {"$last": "$access.type"}}},
{$match: {'_id': readerGroup}}
]);
@omeroot
Copy link
Copy Markdown
Author

omeroot commented Dec 21, 2015

MONGODB AGGREGATE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment