【问题标题】:How to use $subtract with array of document in mongoDB如何在 mongoDB 中使用 $subtract 和文档数组
【发布时间】: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


【解决方案1】:

像这样使用$group 代替$unwind(之前),

聚合管道

db.users.aggregate([
        {
            $unwind: '$orgDta'
        }, {
            $group: {
                _id: '$_id',
                remainingUser: {
                    $push: {
                        $subtract: ['$orgDta.organizationLicence.userCount', '$count']
                    }
                }
            }
        }
    ])

我们在这里做的是展开目标数组,减去所有元素(在您的情况下,元素子元素的元素值),然后将数组与结果(减法)值组合在一起。

在最终结果文档中添加您可能需要的其他项目,上面只是一个示例 MongoDB 聚合查询。

【讨论】:

  • @Nites Singh。谢谢!
猜你喜欢
  • 2016-11-04
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
相关资源
最近更新 更多