簡體   English   中英

MongoDB:將數組中匹配的元素作為字段追加

[英]MongoDB: append as field the matched element from array

我有以下代碼:

const array = ['a', 'b', 'c']

await collection.aggregate([
  { 
    $match: { 
      codes: { $in: array } 
    }
  },
  { 
    $addFields: { matchedField: "codes.$" } // <--- does not work
  }, 
]).toArray();

我需要將數組中匹配的元素附加到返回的結果中。 有可能這樣做嗎?

我的收藏包含具有以下方案的文檔:

{
  "color": "red",
  "codes": [ "b" ]
}

我需要聚合指令來返回這個:

{
  "color": "red",
  "codes": [ "b" ],
  "matchedField": "b",
}

$filter

db.collection.aggregate([
  {
    "$match": {
      "codes": {
        "$in": [
          "a",
          "b",
          "c"
        ]
      }
    }
  },
  {
    "$set": {
      codes: {
        $filter: {
          input: "$codes",
          as: "c",
          cond: {
            $in: [
              "$$c",
              [
                "a",
                "b",
                "c"
              ]
            ]
          }
        }
      }
    }
  }
])

mongoplayground


$setIntersection

db.collection.aggregate([
  {
    "$match": {
      "codes": {
        "$in": [
          "a",
          "b",
          "c"
        ]
      }
    }
  },
  {
    "$set": {
      codes: {
        $setIntersection: [
          "$codes",
          [
            "a",
            "b",
            "c"
          ]
        ]
      }
    }
  }
])

mongoplayground

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM