我遇到了以下数据库结构问题 集合“用户”:
[
{ _id: ObjectId("507f1f77bcf86c0000000001"), name: "Mike", status: "ACTIVE", verified: true },
{ _id: ObjectId("507f1f77bcf86c0000000002"), name: "Ben", status: "INACTIVE", verified: true },
{ _id: ObjectId("507f1f77bcf86c0000000003"), name: "Anastasia", status: "ACTIVE", verified: true }
]
集合“报告”
[
{ userRef: ObjectId("507f1f77bcf86c0000000001"), reportVerified: true },
{ userRef: ObjectId("507f1f77bcf86c0000000003"), reportVerified: false },
]
如您所见,我有一个包含所有用户的集合,另一个名为“报告”的集合是对用户的条目引用,并且具有一个单独的标志字段,称为“ reportVerified”。现在,我想从“用户”集合中找到所有条目,这些条目在“用户”集合中具有特定属性,但在“报告”集合中也具有特定属性。
示例:我想查找所有具有User-Collection.status“ ACTIVE”并在“ Report” -Table中将“ reportVerified”设置为true的引用的用户。在我的情况下,这只能匹配“ Mike”。 对于我来说,直接选择将“报表”集合的属性直接包含在“用户”集合中是不可行的。
如果我只在“用户”集合(简单查找)或“报告”集合(使用填充)中找到了查找条件,但是这种情况我会同时考虑到。
>答案 0 :(得分:1)
最好的方法是使用aggregate
。首先,您需要使用lookup
将用户对象添加到report
对象中。
例如
mongoose.db(dbName).collection(cName).aggregate([
{
$match :{} // your match condition for report
},
{
$lookup:
{
from: "user-collection-name",
let: { user_id: "$_id", user_conditon: "$status" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$userRef", "$$user_id" ] }, // for joining collections
{ $eq: [ conditionInput, "$$status" ] }, // for querying on user collection
]
}
}
}
],
as: "user"
}
}
])