$all 运算符如何与 MongoDB 中的 $elemMatch 一起使用?

How does $all operator works with $elemMatch in MongoDB?

请解释此 MongoDB 查询。

db.inventory.find({ qty : { $all : [ { $elemMatch : { size: "M", num : { $gt : 40},color : "green" }} ,{ $elemMatch : { num :100 , color : "green"}}  ]}}).pretty()

好吧,假设我们有以下文档:

/* 1 */
{
    "_id" : ObjectId("5a148f114d8a2fe38bec772a"),
    "samplearray" : [ 
        {
            "size" : "M",
            "num" : 45,
            "color" : "black"
        }, 
        {
            "size" : "L",
            "num" : 75,
            "color" : "blue"
        }
    ]
}

此处samplearray有两个条目

1

这个查询:

db.sample.find({ samplearray: { $elemMatch: { num: { $gt: 41 }}}})

会return文件。在查询中,我们要求一个数组值条目,其中 num 大于 41.

2

现在,如果我们执行此查询:

db.sample.find({ samplearray: { $elemMatch: { num: { $gte: 50 }, color: "black"}}})

它不应该 return 任何东西。因为 $elemMatch 会查看每个单独的数组值条目。现在文档不匹配。因为在单个数组中我们没有满足这两个条件的数组值条目。在文档中,我们有一个满足 num: { $gte: 50 } 的数组条目(示例:

{
  "size" : "L",
  "num" : 75,
  "color" : "blue"
}

)

还有一个用于 color: "black"(例如:

{
   "size" : "M",
   "num" : 45,
   "color" : "black"
}

) , 但不是两者合二为一。

3

如果我们想得到文档作为结果,那么我们将不得不重写我们的查询,这里是我们引入 $all:

db.sample.find({
    samplearray: {
        $all: [{
                $elemMatch: {
                    num: {
                        $gte: 50
                    }
                }
            },
            {
                $elemMatch: {
                    color: "black"
                }
            }
        ]
    }
})

你现在明白$all$elemMatch好一点了吗?