在MongoDB中,$all用于选择文档,其中字段的值是包含所有指定元素的数组
让我们创建一个包含文档的集合-
> db.demo163.insertOne( ... { ... "ClientDetails": [{ ... "ClientName": "Chris" ... ... }, { ... "ClientName": "David" ... ... } ... ] ... ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e3686d49e4f06af551997c5") } > db.demo163.insertOne( ... { ... "ClientDetails": [{ ... "ClientName": "Mike" ... ... }, { ... "ClientName": "Sam" ... ... } ... ] ... ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e3686d59e4f06af551997c6") } > db.demo163.insertOne( ... { ... "ClientDetails": [{ ... "ClientName": "Robert" ... ... }, { ... "ClientName": "Sam" ... ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e3686d59e4f06af551997c7") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo163.find();
这将产生以下输出-
{ "_id" : ObjectId("5e3686d49e4f06af551997c5"), "ClientDetails" : [ { "ClientName" : "Chris" }, { "ClientName" : "David" } ] } { "_id" : ObjectId("5e3686d59e4f06af551997c6"), "ClientDetails" : [ { "ClientName" : "Mike" }, { "ClientName" : "Sam" } ] } { "_id" : ObjectId("5e3686d59e4f06af551997c7"), "ClientDetails" : [ { "ClientName" : "Robert" }, { "ClientName" : "Sam" } ] }
以下是在MongoDB中对$all的查询-
> db.demo163.find({"ClientDetails": {$all: [{"ClientName": "Mike"}, {"ClientName": "Sam"}]}});
这将产生以下输出-
{ "_id" : ObjectId("5e3686d59e4f06af551997c6"), "ClientDetails" : [ { "ClientName" : "Mike" }, { "ClientName" : "Sam" } ] }