【发布时间】:2021-06-01 19:20:11
【问题描述】:
基本上,我有一个具有以下结构的 Mongo DB:
[
{
"id": 1,
"other_thing": "whatever",
"annoying_array": [
{
"sub_id": "a",
"thing_type": "apple"
},
{
"sub_id": "b",
"thing_type": "pear"
}
]
},
{
"id": 2,
"other_thing": "whatever_else",
"annoying_array": [
{
"sub_id": "c",
"thing_type": "carrot"
},
{
"sub_id": "d",
"thing_type": "pear"
},
{
"sub_id": "e",
"thing_type": "pear"
}
]
}
]
我基本上想做类似db.docs.find( {annoying.array.thing_type: "pear"}) 的事情并让它返回:
[
{
"id": 1,
"other_thing": "whatever",
"annoying_array": [
{
"sub_id": "b",
"thing_type": "pear"
}
]
},
{
"id": 2,
"other_thing": "whatever_else",
"annoying_array": [
{
"sub_id": "d",
"thing_type": "pear"
},
{
"sub_id": "e",
"thing_type": "pear"
}
]
}
]
This question 似乎相关,但已经有将近 10 年的历史了,而且我知道从那时起大量的过滤器/聚合管道发生了变化。可能有一种更清洁的方法。
我已经尝试了所有我能想到的东西,从 find 到 match 和 elemMatch,但所有东西都会返回所有 存在 thing_type: 'pear' 的文档和子数组,而不是thing_type = pear 的子数组中的每个元素。即使它没有返回周围的元数据(即不包括other_thing 等),我也会满足于返回键与特定值匹配的每个元素(子文档)强>。
如果可以选择返回 annoying_array 的每个匹配元素作为其自己的文档匹配,并将文档范围的数据(即 id 或 other_thing)投影到每个匹配。
【问题讨论】:
标签: arrays mongodb filter document