我需要一个查询来查找用户集合中存在的任何具有 groups._id 的文档,该文档不存在于 groups 集合的 _id 中
用户集合 - 文档
{
"_id": ObjectId("65c35a039773c8593fc45ddb"),
"email": "email",
"name": "name",
"groups": [
{
"_id": ObjectId("65c1b7716f130b7c4190104a"),
"name": "testgroup"
}
]
},
{
"_id": ObjectId("65c35a039773c8593fc45ddf"),
"email": "email",
"name": "name",
"groups": [
{
"_id": ObjectId("65c1b7716f130b7c4190104b"),
"name": "testgroup1"
}
]
},
{
"_id": ObjectId("65c35a039773c8593fc45ddc"),
"email": "email",
"name": "name",
"groups": []
}
小组收藏-文档
{
"_id" : ObjectId("65c1b7716f130b7c4190104a"),
"name" : "testgroup",
}
{
"_id" : ObjectId("65c1b7716f130b7c4190104f"),
"name" : "testgroup2",
}
此查询返回匹配的文档,但如何获取不匹配的文档
db.getCollection("users").aggregate([
{ $match: { $expr:{$ne:[0,{ $size: "$groups" }]} } },
{ $lookup: {
from: "groups",
localField: "groups._id",
foreignField: "_id",
as: "matchingDocuments"
}},
{ $project: {
existsInCollection2: { $gt: [{ $size: "$matchingDocuments" }, 0] }
}}
])
一种选择是比较两个数组的大小:
db.users.aggregate([
{$match: {"groups.0": {$exists: true}}},
{$lookup: {
from: "groups",
localField: "groups._id",
foreignField: "_id",
as: "matchingDocuments",
pipeline: [{$project: {_id: 1}}]
}},
{$match: {$expr: {$ne: [{$size: "$groups"}, {$size: "$matchingDocuments"}]}}}
])