我有两个像下面的集合,我很困惑的查询可以任何一个请帮助解决,
组:
var WorkKrewSchema = mongoose.Schema({
content_detail: {
name: String,
description: String
},
business_info: {
name: String,
address: String,
city: String,
state: String,
zipcode: String,
website: String,
starting_hours: Date,
ending_hours: Date,
days: Array
},
created_by: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
created_on: Date,
updated_on: Date
});
成员:
var KrewPartnerSchema = mongoose.Schema({
Work_krew_id: {
type: mongoose.Schema.Types.ObjectId
},
members: [
{
refrence_id: mongoose.Schema.Types.ObjectId,
is_sub_admin: {
type: Boolean,
default: false
},
status: {
type: String,
enum: ['accepted', 'declined', 'pending']
},
date_of_join: Date
}
]
});
获取群组:
答案 0 :(得分:0)
假设您的集合Groups
包含以下格式的文档:
{
"_id" : ObjectId("598311f3c63f57ec3dcac86f"),
"grp_name" : "groupA",
"created_by" : "userA"
}
...以及包含以下格式的文档的集合Members
:
{
"_id" : ObjectId("59831310c63f57ec3dcac891"),
"grp_id" : ObjectId("598311f3c63f57ec3dcac86f"),
"members" : [
{
"user_id" : "UserY",
"status" : "pending"
},
{
"user_id" : "UserA",
"status" : "pending"
},
{
"user_id" : "UserB",
"status" : "approved"
}
]
}
...您可以为名为"UserA"
的用户运行以下查询,该用户应该执行您需要的操作:
db.getCollection('Members').aggregate(
{
$lookup:
{
from: "Groups",
localField: "grp_id",
foreignField: "_id",
as: "group"
}
},
{
$match:
{
$or:
[
{
"members.user_id": { $ne: "UserA" },
"group.0.created_by": { $ne: "UserA" }
},
{
"members":
{
$elemMatch:
{
"user_id": "UserA",
"status": "pending"
}
}
}
]
}
}
)
但我建议您将这两个集合合并为一个集合。组文档应该只包含其所有成员,在这种情况下,您不需要$lookup内容,并且可以使用简单查询(没有聚合框架)。