MongoDB聚合:返回包含匹配值的数组中的对象

kqlmhetl  于 2023-03-01  发布在  Go
关注(0)|答案(1)|浏览(192)

在我的MongoDB聚合管道中,我想从数据中检索一个数字的匹配对象(见下文)

对于此号码“9999933333”,我希望结果如下:

'matchingObjects':[ 
    {
      id:'efg',
      phoneNumbers: ['9999933333','9999944444']
   },
   {
      id:'hij',
      phoneNumbers: ['9999933333','9999955555']
   }
  ]

以下是数据(在前几个阶段之后):

{
 id: 123
 contactsOfAppUsers:[
   {
    id:'abc',
    contactsArray: ['9999911111','9999922222']
   },
   {
    id:'efg',
    contactsArray: ['9999933333','9999944444']
   },
   {
    id:'hij',
    contactsArray: ['9999955555','9999933333']
   }
 ]
}

我试过这个,它给出了布尔值,这不是我想要的。

db.phNumbers.aggregate([
  {// Previous stage},
  {
    $addFields: {
      'matchingObjects': {
        '$map': {
          'input': '$contactsOfAppUsers',
          'as': 'cc',
          'in': {
            '$in': [
              '9999933333','$$cc.contactsArray'
            ]
          }
        }
      }
    }
  },
])
o8x7eapl

o8x7eapl1#

你应该试试这个:

db.collection.aggregate({
  $project: {
    _id: 0,
    matchingObjects: {
      $filter: {
        input: "$contactsOfAppUsers",
        as: "numbers",
        cond: {
          $in: [
            "9999933333",
            "$$numbers.contactsArray"
          ]
        }
      }
    }
  }
})

参见:https://mongoplayground.net/p/Q5xlO1ZOMcb

    • 编辑**

如果确实要将字段重命名为phoneNumbers,请尝试以下操作:

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      matchingObjects: {
        $filter: {
          input: "$contactsOfAppUsers",
          as: "numbers",
          cond: {
            $in: [
              "9999933333",
              "$$numbers.contactsArray"
            ]
          }
        }
      }
    }
  },
  {
    $addFields: {
      matchingObjects: {
        $map: {
          input: "$matchingObjects",
          as: "matchingObjects",
          in: {
            phoneNumbers: "$$matchingObjects.contactsArray",
            id: "$$matchingObjects.id"
          }
        }
      }
    }
  }
])

参见:https://mongoplayground.net/p/cXkFo59YdMy

相关问题