要匹配MongoDB中的文档,请使用$elemMatch。首先让我们创建一个包含文档的集合-
> db.demo15.insertOne({"Details":[{"Score":56},{"Score":78}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e0f7806d7df943a7cec4fab") } > db.demo15.insertOne({"Details":[{"Score":86},{"Score":86}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e0f7817d7df943a7cec4fac") } > db.demo15.insertOne({"Details":[{"Score":97},{"Score":85}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e0f7823d7df943a7cec4fad") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.demo15.find();
这将产生以下输出-
{ "_id" : ObjectId("5e0f7806d7df943a7cec4fab"), "Details" : [ { "Score" : 56 }, { "Score" : 78 } ] } { "_id" : ObjectId("5e0f7817d7df943a7cec4fac"), "Details" : [ { "Score" : 86 }, { "Score" : 86 } ] } { "_id" : ObjectId("5e0f7823d7df943a7cec4fad"), "Details" : [ { "Score" : 97 }, { "Score" : 85 } ] }
这是查找文档的查询,其中文档中数组的所有元素均具有特定值-
> db.demo15.find({ ... "Details.Score" : { ... $exists : true ... }, ... "Details" : { ... $not : { ... $elemMatch : { ... "Score" : { ... $ne : 86 ... } ... } ... } ... } ... });
这将产生以下输出-
{ "_id" : ObjectId("5e0f7817d7df943a7cec4fac"), "Details" : [ { "Score" : 86 }, { "Score" : 86 } ] }