我有一个mongo集合,其中包含以下文档:
{
_id: ObjectId("5c7ba3c0e30e6132f8b0c4ef"),
replies: [
{
_id: ObjectId("5c7ba3c0e30e6132f8b0c4ef"),
status: 'rejected'
}
]
}
我想获得所有已批准状态的答复,因此我进行以下查询:
Collection.find({'replies.status': 'approved'})
,上面的文档仍显示在结果中。我在做什么错了?
答案 0 :(得分:3)
这是对查询过程的常见误解。我怀疑您的其中一个文档看起来像这样:
{
"_id" : 0,
"replies" : [
{ "_id" : "R0", status: "rejected"}
,{ "_id" : "R1", status: "approved"}
]
}
问题在于,在数组上执行find
会匹配数组条目中至少一个匹配的任何文档;它不会将结果过滤为仅这些条目。这是两种方法。鉴于此数据设置:
var r =
[
{
"_id" : 0,
"replies" : [
{ "_id" : "R0", status: "rejected"}
,{ "_id" : "R1", status: "approved"}
]
}
,{
"_id" : 1,
"replies" : [
{ "_id" : "R2", status: "rejected"}
,{ "_id" : "R3", status: "rejected"}
]
}
,{
"_id" : 2,
"replies" : [
{ "_id" : "R4", status: "rejected"}
,{ "_id" : "R5", status: "approved"}
]
}
];
方法1:简单且嵌入式数组很小(条目数不超过100或1000。
db.foo.aggregate([
// This will find all docs where ANY of the replies array has AT LEAST ONE
// entry "approved." It will NOT filter just those.
{$match: {"replies.status": "approved"}}
// Now that we have them, unwind and "refilter"
,{$unwind: "$replies"}
,{$match: {"replies.status": "approved"}}
]);
{ "_id" : 0, "replies" : { "_id" : "R1", "status" : "approved" } }
{ "_id" : 2, "replies" : { "_id" : "R5", "status" : "approved" } }
方法2:如果数组非常大,请使用$filter
,使用$unwind
会创建1000个文档。这种方法在保留原始文档的结构中也很有用:
db.foo.aggregate([
// This will find all docs where ANY of the replies array has AT LEAST ONE
// entry "approved." It will NOT filter just those.
{$match: {"replies.status": "approved"}}
// To avoid $unwind, directly filter just "approved" and reset the replies
// field back into the parent doc:
,{$addFields: {replies: {$filter: {
input: "$replies",
as: "zz",
cond: { $eq: [ "$$zz.status", "approved" ] }
}}
}}
]);
/*
{
"_id" : 0,
"replies" : [
{
"_id" : "R1",
"status" : "approved"
}
]
}
{
"_id" : 2,
"replies" : [
{
"_id" : "R5",
"status" : "approved"
}
]
}
}