如何在mongodb中将其他元素与arrayToObject一起使用?

时间:2019-06-28 07:49:52

标签: mongodb

我试图在我的MongoDB中获取键的所有不同值的计数。我也正在获得计数,但是除了计数之外,我还需要其他详细信息。

   {hobby:"swimming", "name" : "abc", "state" : 'PA', "age":10, "address":"ggg"}
   {hobby:"swimming", "name" : "abc", "state" : 'PA', "age":10, "address":"ggg" }
   {hobby:"swimming", "name" : "def", "state" : 'IA', "age":12, "address":"kkk"  }
   {hobby:"swimming", "name" : "def", "state" : 'IA', "age":12, "address":"kkk"   }
   {hobby:"swimming", "name" : "abc", "state" : 'DA', "age":10, "address":"ggg"  }
   {hobby:"swimming", "name" : "abc", "state" : 'DA', "age":10, "address":"India"  }
   {hobby:"swimming", "name" : "def", "state" : 'DA', "age":12, "address":"kkk"   }
   {hobby:"swimming", "name" : "abc", "state" : 'IA', "age":10, "address":"ggg"  }


     return db.collection.aggregate([
        {"$match":{"hobby":"swimming"}},
        {"$group":
          {
             "_id":{"name":"$name","state":"$state","age":"$age","address":"$address"},
             "count":{"$sum":1}
           }
        },
        {"$group":{
            "_id":"$_id.name",
            "age":"$_id.age",
           "address":"$_id.address",
           "details":{
                "$push":{
                   "k":"$_id.state",
                   "v":"$count"
                }
             }
         }},
         {"$addFields":{
            "details":{
                "$arrayToObject":"$details"
             }
          }}
      ])

当前结果:-

未处理的拒绝,位于:MongoError:字段“ age”必须是累加器对象

预期结果:-

[
  {
     "_id": "def",
     "age":10,
     "address":"ggg",
     "details": {
       "DA": 1,
       "IA": 2
     }
  },
 {
     "_id": "abc",
     "age":12,
     "address":"kkk",
     "details": {
        "DA": 2,
        "IA": 1,
        "PA": 2
     }
  }
]

有人知道如何得到这个吗?

1 个答案:

答案 0 :(得分:1)

错误

  

未处理的拒绝,位于:MongoError:“年龄”字段必须为   蓄电池对象

当我们尝试从同一个对象列表中获取一个对象(键值)时,通常是在MongoDB中的groupBy组中时出现的

db.collection.aggregate([
  {
    "$match": { "hobby": "swimming" }
  },
  { "$group": {
      "_id": { "name": "$name", "state": "$state", 
                "age": "$age", "address": "$address"},
      "count": { "$sum": 1 }
    }
  },
  {
    "$group": {
      "_id": "$_id.name",
      "age": { $first: "$_id.age" },       
      "address": { $first: "$_id.address" },
      "details": {
        "$push": { "k": "$_id.state", "v": "$count" }
       }
    }
  },
  {
    "$addFields": {
      "details": { "$arrayToObject": "$details" }
    }
  }
])

这行代码是错误的,因为他们更反对从他们那里获取年龄或地址元素

"age": "$_id.age",       
"address": "$_id.address",

所以现在我们选择first对象

"age": { $first: "$_id.age" },       
"address": { $first: "$_id.address" },

您可以选中here