mongodb 如何在mongo中获取数组中对象的长度?

bvk5enib  于 2023-01-20  发布在  Go
关注(0)|答案(2)|浏览(182)

我的数据库结构是这样的:model of messages in db每个文档都有“对象”类型的“接收者编号”字段:

receiverNumbers: {
  type: [{type: Object}],
  required: true
},

在该对象中,我们具有两个属性。“phoneNumber”和“resultSend”,其中resultSend是具有很少属性对象。
如何获得“resultSend”对象的“send”属性为true的所有文档的receiverNumbers的长度?
我知道我应该使用聚合,但我不知道如何使用。

rsaldnfx

rsaldnfx1#

考虑到您的输入文档如下所示:

{
  "_id": "id_1",
  "User": "user_1",
  "TotalNumber": 50,
  "SuccessNumber": 50,
  "__v": 0,
  "receiverNumbers": [
    {
      "phoneNumber": "01 23 45 67 89",
      "resultSend": {
        "senderNumber": "00 00 00 00 00",
        "messageText": "Hello World sent 1",
        "dateTime": "2023-01-18",
        "send": true
      }
    },
    {
      "phoneNumber": "01 23 45 67 89",
      "resultSend": {
        "senderNumber": "00 00 00 00 00",
        "messageText": "Hello World sent 2",
        "dateTime": "2023-01-18",
        "send": true
      }
    },
    {
      "phoneNumber": "01 23 45 67 89",
      "resultSend": {
        "senderNumber": "00 00 00 00 00",
        "messageText": "Hello World not sent 1",
        "dateTime": "2023-01-18",
        "send": false
      }
    },
    {
      "phoneNumber": "01 23 45 67 89",
      "resultSend": {
        "senderNumber": "00 00 00 00 00",
        "messageText": "Hello World sent 3",
        "dateTime": "2023-01-18",
        "send": true
      }
    },
    {
      "phoneNumber": "01 23 45 67 89",
      "resultSend": {
        "senderNumber": "00 00 00 00 00",
        "messageText": "Hello World not sent 2",
        "dateTime": "2023-01-18",
        "send": false
      }
    },
    
  ]
}

并且您希望每个文档都有receiverNumbers中元素的数量,其中element.resultsend.send为真。
你可以这样做:

db.collection.aggregate([
  {
    "$addFields": {
      "totalSend": {
        $sum: {
          "$map": {
            "input": "$receiverNumbers",
            "as": "val",
            "in": {
              $cond: [
                "$$val.resultSend.send",
                1,
                0,
                
              ]
            }
          }
        }
      }
    }
  }
])

您可以检查https://mongoplayground.net/p/crlKjIcmcWR以进行测试。
如果这回答了你的问题就告诉我。

rxztt3cl

rxztt3cl2#

你可以试试这样的方法:

db.collection.aggregate([
  { $match: { "receiverNumbers.resultSend.send": true } },
  { $project: { length: { $size: "$receiverNumbers" } } },
]);

相关问题