MongoDB 匹配包含数组字段的文档以及与查询匹配的所有元素

mic*_*lem 2 mongodb nosql node.js

来自 MongoDB 文档$elementMatch

$elemMatch 运算符匹配包含数组字段的文档,该数组字段至少有一个元素与所有指定的查询条件匹配。

但是如何将包含数组字段的文档与与查询匹配的所有元素相匹配?

例如我有这样的文档:

{
    "_id": ObjectId("55c99649b8b5fc5b0a2f1c83"),
    "sku": "ed-39211",
    "created_at": ISODate("2015-08-11T06:29:29.139+0000"),
    "formats": [{
        "name": "thefile",
        "_id": ObjectId("55c99649f2e2d6353348ec9c"),
        "prices": [{
            "price": 4.49,
            "currency": "GBP",
            "territory": "GB",
            "_id": ObjectId("55c99649f2e2d6353348ec9f")
        }, {
            "price": 6.99,
            "currency": "USD",
            "territory": "US",
            "_id": ObjectId("55c99649f2e2d6353348ec9e")
        }, {
            "price": 6.99,
            "currency": "CHF",
            "territory": "CH",
            "_id": ObjectId("55c99649f2e2d6353348ec9d")
        }]
    }]
}
Run Code Online (Sandbox Code Playgroud)

我需要匹配所有具有>formats.prices.price 5的文档

如果我使用以下查询:

{ 'formats.prices': { $elemMatch: { price: { $gte: 5 } } } }
Run Code Online (Sandbox Code Playgroud)

该文档将被匹配,因为至少有一个价格 > 5

我也尝试过这个,但似乎不起作用:

{ 'formats.prices': { $all: { $elemMatch: {price: { $gte: 0.98 } } } } }
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以排除查看所有价格而不是至少一个价格的该文档?

mic*_*lem 5

找到了!这很简单,只需使用$not运算符并检查相反的值(< 5):

{ 'formats.prices': { $not: { $elemMatch: {price: { $lt: 5 } } } } }
Run Code Online (Sandbox Code Playgroud)