$elemMatch 过滤后是否可以根据数组的大小返回记录?
例如,如果我的集合中有许多记录,如下所示:
[
{
contents: [
{
name: "yorkie",
},
{
name: "dairy milk",
},
{
name: "yorkie",
},
]
},
// ...
]
我想查找 contents
字段包含 2 个数组项且 name
字段等于“yorkie”的所有记录,我该怎么做?澄清一下,数组可以包含其他项目,但只要其中 2 个数组项目具有匹配的 field:value,就满足条件。
我知道我可以使用 $elemMatch
(或 contents.name
)返回数组中至少包含一项与该名称匹配的项目的记录,并且我'我知道我还可以使用 $size
根据记录字段中数组项的确切数量进行过滤。有没有办法将它们两者结合起来?
最佳答案
不在 find
查询中,但可以通过聚合来完成:
db.test.aggregate([
{ "$match" : { "contents.name" : "yorkie" } },
{ "$unwind" : "$contents" },
{ "$match" : { "contents.name" : "yorkie" } },
{ "$group" : { "_id" : "$_id", "sz" : { "$sum" : 1 } } }, // use $first to include other fields
{ "$match" : { "sz" : { "$gte" : 2 } } }
])
我解释了
the criteria is met so long as 2 of those array items have the matching field:value
这意味着如果至少有 2 个数组项在 name
中具有匹配的值,则满足条件。
关于arrays - 查找查询 - 在 $elemMatch 之后按数组大小过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29615947/