$all$all操作符选择字段值与所有指定值匹配的文档。匹配的文档可以包含一个值为包含所有指定元素的大量的字段,也可以包含一个具有与指定元素匹配的单个值的字段。
兼容性
可以使用 $all 查找托管在以下环境中的部署:
MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
要指定 $all 表达式,请使用以下原型:
{ <field>: { $all: [ <value1> , <value2> ... ] } }
行为
相当于 $and 操作
$all$and相当于指定值的 操作。示例,以下两个查询是等效的:
{ tags: { $all: [ "ssl" , "security" ] } } { $and: [ { tags: "ssl" }, { tags: "security" } ] }
嵌套数组
当传递嵌套大量的大量时(例如 [ [ "A" ] ] ), $all会匹配字段包含嵌套大量作为元素的文档(例如 field: [ [ "A" ], ... ] ),或者字段等于嵌套大量(例如 field: [ "A" ] )。
例如,考虑以下查询:
db.articles.find( { tags: { $all: [ [ "ssl", "security" ] ] } } )
此查询相当于:
db.articles.find( { $and: [ { tags: [ "ssl", "security" ] } ] } )
它相当于:
db.articles.find( { tags: [ "ssl", "security" ] } )
因此, $all表达式匹配tags字段为包含嵌套大量[ "ssl",
"security" ]的大量或是等于嵌套大量的大量的文档:
tags: [ [ "ssl", "security" ], ... ] tags: [ "ssl", "security" ]
空数组
当传递空数组时,$all 不匹配任何文档。
示例
本页上的示例使用sample_mflix示例数据集中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载示例数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。
使用 $all 匹配值
以下操作使用$all 操作符在movies 集合中查询文档,其中directors 字段的值是元素包括John Murray Anderson 和Pèl Fejès 的大量:
db.movies.find( { directors: { $all: ['John Murray Anderson','Pèl Fejès'] } }, { title: 1, directors: 1, year: 1 })
上述查询返回以下文档:
[ { _id: ObjectId('573a1391f29313caabcd9336'), title: 'King of Jazz', directors: [ 'John Murray Anderson', 'Pèl Fejès' ], year: 1930 } ]
将 $all 与 $elemMatch 结合使用
要匹配单个大量元素或文档大量的多个条件,可以将$all 与$elemMatch 操作符一起使用。
以下操作会在 embedded_movies集合中查询符合以下条件的文档:
至少一名写入者有
story信用,但没有screenplay信用至少一名写入者有
titles信用,但没有adaptation信用
db.embedded_movies.find( { writers: { $all: [ { $elemMatch: { $regex: '\\bstory\\b', $not: { $regex: '\\bscreenplay\\b' }}}, { $elemMatch: { $regex: '\\btitles\\b', $not: { $regex: '\\badaptation\\b' }}} ]}}, { title: 1, writers: 1, year: 1 })
该查询返回以下文档:
[ { "_id": { "$oid": "573a1391f29313caabcd93a3" }, "title": "Men Without Women", "writers": [ "John Ford (story)", "James Kevin McGuinness (story)", "Dudley Nichols (screen play and scenario)", "Otis C. Freeman (titles)" ], "year": 1930 }, { "_id": { "$oid": "573a1391f29313caabcd8319" }, "title": "For Heaven's Sake", "writers": [ "Ted Wilde (story)", "John Grey (story)", "Clyde Bruckman (story)", "Ralph Spence (titles)" ], "year": 1926 }, { "_id": { "$oid": "573a1391f29313caabcd7bc3" }, "title": "The Iron Horse", "writers": [ "Charles Kenyon (story)", "John Russell (story)", "Charles Kenyon (scenario)", "Charles Darnton (titles)" ], "year": 1924 } ]
注意
大多数情况下,MongoDB 不会将数组视作集合。此运算符为这种方法提供了一个值得注意的例外。
其他示例
有关查询数组的其他示例,请参阅:
有关查询的其他示例,请参阅查询文档。