首页 > 解决方案 > 嵌套数组查询不适用于 Mongoose

问题描述

我有一个mongo文档

{
    "locationId": "5f2084f756dc2428e96fcda4",
    "information": [{
        "category": ["5e5150c6c52a3904b74d6ff7"],     
        "date": {
            "$date": {
                "$numberLong": "1601407317343"
            }
        },
        "private": true
    }, {     
     "category": ["5e5150c6c52a3904b74d6ff7"], 
        "date": {
            "$date": {
                "$numberLong": "1601407317343"
            }
        },
        "private": false
    },
    }],
}

到目前为止,我所拥有的是查询嵌套数组。

const f = await info.aggregate([
  {
    $match: {
      $and: [
          {'locationId': '5f2084f756dc2428e96fcda4'},
          {'information.private': true}
      ]
    },
  },
]);

我正在尝试查询information.private = true。但是,我同时收到“私人:假”和“私人:真”。结果是

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "information": [
      {
        "category": [
          "5e5150c6c52a3904b74d6ff7"
        ],
        "date": ISODate("2020-09-29T19:21:57.343Z"),
        "private": true
      },
      {
        "category": [
          "5e5150c6c52a3904b74d6ff7"
        ],
        "date": ISODate("2020-09-29T19:21:57.343Z"),
        "private": false
      }
    ],
    "locationId": "5f2084f756dc2428e96fcda4"
  }
]

我也尝试使用 elemMatch 并返回相同的结果。我在 Stackoverflow 上查找了多个答案,但点符号和 elemMatch 在这种情况下不起作用。我知道我做错了什么,但我无法弄清楚。

标签: mongodbmongoose

解决方案


你可以$filter试试

  • $match你的条件
  • $addFields添加字段信息并$filter迭代数组循环并根据条件获取匹配文档
const f = await info.aggregate([
  {
    $match: {
      locationId: "5f2084f756dc2428e96fcda4",
      "information.private": true
    }
  },
  {
    $addFields: {
      information: {
        $filter: {
          input: "$information",
          cond: { $eq: ["$$this.private", true] }
        }
      }
    }
  }
])

操场


您可以尝试其他选项$redact

  • $match你的情况
  • $redact根据存储在文档本身中的信息限制文档的内容。
const f = await info.aggregate([
  { $match: { locationId: "5f2084f756dc2428e96fcda4" } },
  {
    $redact: {
      $cond: [{ $eq: ["$private", false] }, "$$PRUNE", "$$DESCEND"]
    }
  }
])

操场


find 投影可以接受从 MongoDB 4.4 开始的聚合表达式和语法。

const f = await info.find([
  locationId: "5f2084f756dc2428e96fcda4",
  "information.private": true
},
{
  locationId: 1,
  information: {
    $filter: {
      input: "$information",
      cond: { $eq: ["$$this.private", true] }
    }
  }
})

操场


推荐阅读