我是 mongodb 新手。假设如下。一个集合 x、y 和 z 中有 3 种类型的文档。
docs = [{
"item_id": 1
"type": "x"
},
{
"item_id": 2
"type": "x"
},{
"item_id": 3
"type": "y",
"relavent_item_ids": [1, 2]
},
{
"item_id": 3
"type": "y",
"relavent_item_ids": [1, 2, 3]
},{
"item_id": 4
"type": "z",
}]
我想要得到以下内容。
- 忽略类型为
z
的文档 - 获取
x
类型的所有文档它在哪里item_id
不在relavent_item_ids
中类型y
文件。 - 结果应为
item_id
领域。
我尝试做 match
$in
但这会返回所有记录,我无法弄清楚如何处理 y
类型的文档子集.
最佳答案
您可以使用以下查询
const item_ids = (await db.collection.find({ "type": "y" })).map(({ relavent_item_ids }) => relavent_item_ids)
const result = db.collection.find({
"item_id": { "$exists": true },
"type": { "$ne": "z", "$eq": "x" },
"relavent_item_ids": { "$nin": item_ids }
})
console.log({ result })
忽略类型为 z 的文档 --> 使用 $ne
不等于查询运算符来过滤 z
类型。
获取 x 类型的所有文档,其中 item_id 不在 y 类型文档的 relavent_item_ids 中 --> 使用 $expr
匹配相同的文档字段。
结果应该有 item_id 字段 --> 使用 $exists
查询运算符。
关于mongodb - Mongodb 不在查询中,因为具有来自同一集合的两个文档子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59526214/