MongoDB 查询匹配包含数组字段的文档
若要匹配包含数组字段的文档,请使用 $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" } ] }
广告