mongodb 是否有任何mongo数据库查询只获取搜索元素所有嵌套元素

pobjuy32  于 2023-01-25  发布在  Go
关注(0)|答案(1)|浏览(66)

数据结构是

[
  {
    "item": "journal",
    "qty": 25,
    "status": "A",
    "weekNumber": 1,
    "sortOrder": 1,
    "label": 1,
    "numberOfPossibleDays": 1,
    "editable": 1,
    "selectedDate": 1,
    "deliveryDays": 1,
    "products": [
      {
        "key": "item-one",
        "name": "item one",
        "tags": [
          "v",
          "b"
        ]
      },
      {
        "key": "item-two",
        "name": "item-two",
        "tags": [
          "a",
          "c",
          "d"
        ]
      },
      {
        "_id": 3,
        "name": "item-three",
        "tags": [
          "g"
        ]
      }
    ]
  },
  {
    "item": "notebook",
    "status": "b",
    "qty": 1,
    "weekNumber": 1,
    "sortOrder": 1,
    "label": 1,
    "numberOfPossibleDays": 1,
    "editable": 1,
    "selectedDate": 1,
    "deliveryDays": 1,
    "products": [
      {
        "key": "item-four",
        "name": "item four",
        "tags": [
          "a",
          "o"
        ]
      },
      {
        "key": "item-five",
        "name": "item-five",
        "tags": [
          "s",
          "a",
          "b"
        ]
      }
    ]
  }
]

我想找到所有带有标签'a'的元素,所以预期的响应应该是

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "deliveryDays": 1,
    "editable": 1,
    "item": "journal",
    "label": 1,
    "numberOfPossibleDays": 1,
    "products": [
      {
        "key": "item-one",
        "name": "item one",
        "tags": [
          "v",
          "b"
        ]
      }
    ],
    "qty": 25,
    "selectedDate": 1,
    "sortOrder": 1,
    "status": "A",
    "weekNumber": 1
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "deliveryDays": 1,
    "editable": 1,
    "item": "notebook",
    "label": 1,
    "numberOfPossibleDays": 1,
    "products": [],
    "qty": 1,
    "selectedDate": 1,
    "sortOrder": 1,
    "status": "b",
    "weekNumber": 1
  }
]

我可以使用$filter操作符来过滤tags数组中包含“B”的元素,以获得投影中的products数组。我认为这是非常冗长的代码。有没有什么方法可以让mongoDB发送所有的值,而不是像这样写入查询中的每个元素?

db.collection.find({
  "products.tags": "b"
},
{
  item: 1,
  qty: 1,
  "status": 1,
  "weekNumber": 1,
  "sortOrder": 1,
  "label": 1,
  "numberOfPossibleDays": 1,
  "editable": 1,
  "selectedDate": 1,
  "deliveryDays": 1,
  products: {
    $filter: {
      input: "$products",
      cond: {
        $in: [
          "v",
          "$$this.tags"
        ]
      }
    }
  }
})
ntjbwcob

ntjbwcob1#

你可以使用如下的聚合:

db.collection.aggregate([
  {
    $match: {
      "products.tags": "b"
    },
    
  },
  {
    $set: {
      products: {
        $filter: {
          input: "$products",
          cond: {
            $in: [
              "v",
              "$$this.tags"
            ]
          }
        }
      }
    }
  }
])

它将给予与前面相同的结果,但您不必用field : 1写入每个字段来保留它们。

相关问题