MongoDB 查询包含 $all 数组
在 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" } ] }
广告