Mongodb 嵌套数组查询不适用于Mongoose
我有一份mongo的文件Mongodb 嵌套数组查询不适用于Mongoose,mongodb,mongoose,Mongodb,Mongoose,我有一份mongo的文件 { "locationId": "5f2084f756dc2428e96fcda4", "information": [{ "category": ["5e5150c6c52a3904b74d6ff7"], "date": { "$date": {
{
"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}
]
},
},
]);
我正在尝试查询信息。private=true
。但是,我同时收到“private:false”和“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在这种情况下不起作用。我知道我做错了什么,但我想不出来。你可以试试
$filter
您的条件$match
添加字段信息和$addFields
迭代数组循环并根据条件获取匹配文档$filter
其他选项您可以尝试
$redact
您的条件$match
根据文档本身存储的信息限制文档的内容$redact
可以接受从MongoDB 4.4开始的聚合表达式和语法
const f = await info.find([
locationId: "5f2084f756dc2428e96fcda4",
"information.private": true
},
{
locationId: 1,
information: {
$filter: {
input: "$information",
cond: { $eq: ["$$this.private", true] }
}
}
})
information.private不起作用有什么原因吗?这是一种行为,我们不能直接从匹配条件访问数组元素,匹配只会匹配条件。它将返回数组元素匹配的整个文档。当我使用.find()时也会发生这种情况。我是否必须始终获取文档并将其计算出来?如果您知道数组中有单个元素,而我只需要一个,那么您可以使用
find({“information.private”:true},{“information.$”:1})
这将从数组中返回单个匹配元素,这是唯一有限的选项,否则您可以使用aggregate()和我的答案一样,在mongodb4.4中的find()方法中又添加了一个选项。
const f = await info.aggregate([
{ $match: { locationId: "5f2084f756dc2428e96fcda4" } },
{
$redact: {
$cond: [{ $eq: ["$private", false] }, "$$PRUNE", "$$DESCEND"]
}
}
])
const f = await info.find([
locationId: "5f2084f756dc2428e96fcda4",
"information.private": true
},
{
locationId: 1,
information: {
$filter: {
input: "$information",
cond: { $eq: ["$$this.private", true] }
}
}
})