在MongoDB聚合管道中,如何投影匹配的嵌入式数组的索引



在 mongodb 聚合管道中,我想$project与前一个$match阶段匹配的嵌入式数组(子文档(的索引。

说,我有以下文档。

{_id: '1', tags: ['aaa', 'bbb', 'ccc']},
{_id: '2', tags: ['baa', 'aaa', 'aaa']},
{_id: '3', tags: ['aac', 'cbb', 'aca']},

现在,如果我使用 {tags: 'aaa'} 查询,我想输出类似于

{_id: '1', tags: [0]},
{_id: '2', tags: [1, 2]}
db.inventory.aggregate([
  { $match : {tags : 'aaa' }},
  { $unwind : { path: "$tags", includeArrayIndex: "arrayIndex"}},
  { $match : {tags : 'aaa' }},
  { $group : {
      _id : '$_id',
      tags : { $push : '$arrayIndex'}
    }
  }
 ])

输出:

{ "_id" : "2", "tags" : [ NumberLong(1), NumberLong(2) ] }
{ "_id" : "1", "tags" : [ NumberLong(0) ] }

另一种方式:

db.inventory.aggregate([
 { $match : {tags : 'aaa' }},
 { $project  : {
    tags: {
      $filter: {
        input: {
          $zip: {
            inputs: [ "$tags", { $range: [0, { $size: "$tags" }] } ]
          }
        },
        as: "tagWithIndex",
        cond: {
          $let: {
            vars: {
              tag : { $arrayElemAt: [ "$$tagWithIndex", 0 ] }
            },
            in: { $eq: [ "$$tag", 'aaa' ] }
          }
        }
      }
    }
 }},
 { $unwind  : '$tags'},
 { $group : {
       _id : '$_id',
       tags  : {
          $push : { $arrayElemAt: [ "$tags", 1]}
       }
   }
 }
])

输出:

{ "_id" : "2", "tags" : [ 1, 2 ] }
{ "_id" : "1", "tags" : [ 0 ] }

希望这有帮助。

您需要$map $tags数组的$size以包含tags数组中每个元素的索引,然后您可以轻松地使用$filter聚合来排除包含字母aaa的元素

db.collection.aggregate([
  { "$match": { "tags": "aaa" }},
  { "$project": {
    "tags": {
      "$filter": {
        "input": {
          "$map": {
            "input": { "$range": [0, { "$size": "$tags" }] },
            "in": {
              "string": { "$arrayElemAt": ["$tags", "$$this"] },
              "index": "$$this"
            }
          }
        },
        "cond": { "$eq": ["$$this.string", "aaa"] }
      }
    }
  }},
  { "$project": { "tags": "$tags.index" }}
])

输出

[
  {
    "_id": "1",
    "tags": [0]
  },
  {
    "_id": "2",
    "tags": [1, 2]
  }
]

如果要搜索数组,则应使用 $in。

db.inventory.find( { tags: { $in: [ 'aaa' ] } } )

您也可以在匹配中写相同的内容。 拼写相同。

将帮助细节。这就是你要找的。

来源 : https://docs.mongodb.com/manual/reference/operator/query/in/


db.inventory.find( { "tags": { $in: 'aaa' } },
                  { "tags.$": 1 } )

这可能是你想要的。

最新更新