Reputation: 13345
When I run this command :
db.runCommand(
{
aggregate:"myColl",
pipeline:[
{
$group:{
_id:{os_name:"$os_name",os_version:"$os_version"},
"events.login":{$sum:"$events.login"},
count:{$sum:NumberInt(1)}}
}
],
cursor:{}
}
)
I receive the error:
The field name 'events.login' cannot contain '.'
How can i do to keep the '.' in the returned field name (ie: events.login
)
Upvotes: 0
Views: 174
Reputation: 17915
It's not quiet clear what you're trying to do, So look at these :
Error :
The field name 'events.login' cannot contain '.'
It's because as in $group
stage when it creates a new field on each document for a given name, You'll not be able to create it like this : "events.login"
means cannot create a sub-doc it has to be an object to a top level field events
basically you can not use .
notation, So to make it work you need to have one more stage like this :
db.collection.aggregate([{
$group: {
_id: { os_name: "$os_name", os_version: "$os_version" },
"events": { $sum: "$events.login" },
count: { $sum: NumberInt(1) }
}
}, { $addFields: { 'events.login': '$events' } }])
Test : MongoDB-Playground
If in a case you need to update login
field inside events
field & to retain all other fields inside events
, try below query which would get last document in iteration of each _id
(this will last document inserted to DB on that _id
criteria) & append login
to it :
db.collection.aggregate([{
$group: {
_id: { os_name: "$os_name", os_version: "$os_version" },
"login": { $sum: "$events.login" }, 'events': { $last: '$events' },
count: { $sum: NumberInt(1) }
}
}, { $addFields: { 'events.login': '$login' } }, { $project: { login: 0 } }])
Test : MongoDB-Playground
Upvotes: 1