mongodb - Mongo db 通过拥有来自同一集合的两个文档子集不在查询中
问题描述
我是 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
,但这会返回我所有的记录,我无法弄清楚如何使用 type 的文档子集来保持状态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 类型文档的 relvent_item_ids 中-->$expr
用于匹配相同的文档字段。
结果应该有 item_id 字段--> 使用$exists
查询运算符。