Reputation: 937
We have two collections in which have users and organizations.
db.users.aggregate([
{$match: {"organization.metaInfo":{"$ne": "disabled"}}},
{"$unwind":"$organization"},
{"$group":{"_id":"$organization.organizationId", "count":{"$sum":1}}},
{$lookup: {from: "organisations",
localField: "_id",
foreignField: "_id", as: "orgDta"}},
{"$project":{"_id":1, "count":1,
"orgDta.organizationLicence.userCount":1
}}
])
When this query is performed return a result like which is good to me.
{
"_id" : "768d3090-d4f5-11e7-a503-9b68b90cdb4e",
"count" : 5.0,
"orgDta" : [{
"organizationLicence" : {
"userCount" : 50
}
}]
},
{
"_id" : "d9933740-c29c-11e7-9481-b52c5f3e2e70",
"count" : 1.0,
"orgDta" : [{
"organizationLicence" : {
"userCount" : 1
}
}]
},
{
"_id" : "5386ebc0-c29b-11e7-9481-b52c5f3e2e70",
"count" : 1.0,
"orgDta" : [{
"organizationLicence" : {
"userCount" : 1
}
}]
}
Now, I want to perform a subtract operation in between count and userCount.But I don't know that how to use here.
I was trying together with $project
{"$project":{"_id":1, "count":1, "orgDta.dObjects":1, "orgDta.organizationLicence.userCount":1, "remainingUser": { $subtract: [ "$orgDta.organizationLicence.userCount", "$count"]}
But Mongo returns error
{ "message" : "cant $subtract adouble from a array", "stack" : "MongoError: cant $subtract adouble from a array" }
Upvotes: 2
Views: 1492
Reputation: 1750
Use $group
instead wih $unwind
(before) like this,
Aggregate pipeline
db.users.aggregate([
{
$unwind: '$orgDta'
}, {
$group: {
_id: '$_id',
remainingUser: {
$push: {
$subtract: ['$orgDta.organizationLicence.userCount', '$count']
}
}
}
}
])
What we are doing here is unwind the target array, subtract all the elements (in your case, the element child's element value) and then group the array back with result (of substraction) value.
Add other items you might want in your final result document, above is just a sample MongoDB aggregate query.
Upvotes: 1