要匹配包含数组字段的文档,请使用$ elemMatch运算符。让我们创建一个包含文档的集合-
> db.demo592.insertOne( ... { ... "id":101, ... "details" : [ ... { "Name" : "Chris", "Value" : "200"}, ... {"Name" : "David", "Value" : "800"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e930d8ffd2d90c177b5bcd6") } > db.demo592.insertOne( ... { ... id:102, ... "details" : [ ... { "Name" : "Chris", "Value" : "500"}, ... {"Name" : "David", "Value" : "900"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e930d90fd2d90c177b5bcd7") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo592.find();
这将产生以下输出-
{ "_id" : ObjectId("5e930d8ffd2d90c177b5bcd6"), "id" : 101, "details" : [ { "Name" : "Chris", "Value" : "200" }, { "Name" : "David", "Value" : "800" } ] } { "_id" : ObjectId("5e930d90fd2d90c177b5bcd7"), "id" : 102, "details" : [ { "Name" : "Chris", "Value" : "500" }, { "Name" : "David", "Value" : "900" } ] }
以下是要匹配的查询-
> db.demo592.find( ... { ... "$and" : [ ... { "details" : { "$elemMatch" : { "Name" : "Chris", "Value" : { "$gte" : "500" } } } }, ... { "details" : { "$elemMatch" : { "Name" : "David", "Value" : { "$gte" : "600" } } } } ... ] ... } ... );
这将产生以下输出-
{ "_id" : ObjectId("5e930d90fd2d90c177b5bcd7"), "id" : 102, "details" : [ { "Name" : "Chris", "Value" : "500" }, { "Name" : "David", "Value" : "900" } ] }