【发布时间】:2018-06-29 19:40:34
【问题描述】:
我们有两个集合,其中有用户和组织。
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
}}
])
当这个查询被执行时,返回一个对我有好处的结果。
{
"_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
}
}]
}
现在,我想在 count 和 userCount 之间进行减法运算。但是我不知道如何在这里使用。
我正在尝试与 $project
{"$project":{"_id":1, "count":1, "orgDta.dObjects":1, "orgDta.organizationLicence.userCount":1, "remainingUser": { $subtract: [ "$orgDta.organizationLicence.userCount", "$count"]}
但是 Mongo 返回错误
{ "message" : "cant $subtract adouble from a array", "stack" : "MongoError: cant $subtract adouble from a array" }
【问题讨论】:
-
你为什么要放松和分组
organization?你能解释一下你的要求吗?顺便说一句,当 userCount 数组只有 1 个元素时,您可以使用$arrayElemAt投影第一个元素。试试"remainingUser": { $subtract: [ {$arrayElemAt:["$orgDta.organizationLicence.userCount",0]}, "$count"]}]`
标签: node.js mongodb mongoose aggregate