对于MongoDB中字段的所有元素,请使用,find()
并在其中使用$elemMatch。的$elemMatch操作者匹配包含与匹配的所有指定的查询标准中的至少一个元素的数组字段的文档。
让我们创建一个包含文档的集合-
> db.demo624.insertOne({"ListOfName":["John","Chris","David","Bob"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ab3ff6c954c74be91e6a5") } > db.demo624.insertOne({"ListOfName":["John","Chris"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ab4026c954c74be91e6a6") } > db.demo624.insertOne({"ListOfName":["John","Chris","Carol"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ab4076c954c74be91e6a7") } > db.demo624.insertOne({"ListOfName":["John","Chris","Bob"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ab40e6c954c74be91e6a8") } > db.demo624.insertOne({"ListOfName":["John","Chris","Mike","Robert"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ab4186c954c74be91e6a9") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo624.find();
这将产生以下输出-
{ "_id" : ObjectId("5e9ab3ff6c954c74be91e6a5"), "ListOfName" : [ "John", "Chris", "David", "Bob" ] } { "_id" : ObjectId("5e9ab4026c954c74be91e6a6"), "ListOfName" : [ "John", "Chris" ] } { "_id" : ObjectId("5e9ab4076c954c74be91e6a7"), "ListOfName" : [ "John", "Chris", "Carol" ] } { "_id" : ObjectId("5e9ab40e6c954c74be91e6a8"), "ListOfName" : [ "John", "Chris", "Bob" ] } { "_id" : ObjectId("5e9ab4186c954c74be91e6a9"), "ListOfName" : [ "John", "Chris", "Mike", "Robert" ] }
以下是查询以查看字段的所有元素是否包含在超集中-
> db.demo624.find({"ListOfName":{$not:{$elemMatch:{$nin:["John", "Chris", "David", "Bob"]}}}});
这将产生以下输出-
{ "_id" : ObjectId("5e9ab3ff6c954c74be91e6a5"), "ListOfName" : [ "John", "Chris", "David", "Bob" ] } { "_id" : ObjectId("5e9ab4026c954c74be91e6a6"), "ListOfName" : [ "John", "Chris" ] } { "_id" : ObjectId("5e9ab40e6c954c74be91e6a8"), "ListOfName" : [ "John", "Chris", "Bob" ] }