问题
I have the following kind of docs in a collection in mongo db
{ _id:xx,
iddoc:yy, type1:"sometype1", type2:"sometype2", date: { year:2015, month:4, day:29, type:"day" }, count:23 }
I would like to do a sum over the field count grouping by iddoc for all docs where:
type1 in ["type1A","type1B",...] where type2 in ["type2A","type2B",...] date.year: 2015, date.month: 4, date.type: "day" date.day between 4 and 7
I would like then to sort these sums.
I know now how to do this (see this question)
db.test.aggregate([
// Filter the docs based on your criteria
{$match: {
type1: {$in: ['type1A', 'type1B']},
type2: {$in: ['type2A', 'type2B']},
'date.year': 2015,
'date.month': 4,
'date.type': 'day',
'date.day': {$gte: 4, $lte: 7}
}},
// Group by iddoc and count them
{$group: {
_id: '$iddoc',
sum: {$sum: 1}
}},
// Sort by sum, descending
{$sort: {sum: -1}}
])
but would like some of the fields in the match operation to appear in the final document. Is this possible? How?
回答1:
I believe that this query is a solution for what you are asking:
db.test.aggregate([
// Filter the docs based on your criteria
{$match: {
type1: {$in: ['type1A', 'type1B']},
type2: {$in: ['type2A', 'type2B']},
'date.year': 2015,
'date.month': 4,
'date.type': 'day',
'date.day': {$gte: 4, $lte: 7}
}},
// Group by iddoc and type1 and count them
{$group: {
_id: { iddoc: '$iddoc', type1: '$type1' },
sum: {$sum: 1},
type2: { $push: '$type2' },
year: { $first: '$date.year' },
month: { $first: '$date.month' },
day: { $addToSet: '$date.day' }
}},
// Sort by sum, descending
{$sort: {sum: -1}}
])
There are some options with how you want to see the rest of the fields. I chose to push the type2 to an array (allowing for duplicates), take the first value for year
and month
since those will always be 2015 and 4 per your match operation, and addToSet
the day to an array (not allowing for duplicates).
Another option would be to push the entire document into an array of matches, but one should be careful with that on large collections.
{$group: {
_id: { iddoc: '$iddoc', type1: '$type1' },
sum: {$sum: 1},
matches: { $push: '$$ROOT' }
}},
来源:https://stackoverflow.com/questions/27907573/keeping-field-in-mongodb-group-by