为了更快地搜索,请创建索引。为此,请使用createIndex()
。让我们创建一个包含文档的集合-
> db.demo661.createIndex({ListOfName:1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo661.insertOne({_id:1,ListOfName:["John","Robert","David"]}); { "acknowledged" : true, "insertedId" : 1 } > db.demo661.insertOne({_id:2,ListOfName:["Mike","Sam"]}); { "acknowledged" : true, "insertedId" : 2 } > db.demo661.insertOne({_id:3,ListOfName:["John","David","Bob"]}); { "acknowledged" : true, "insertedId" : 3 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo661.find();
这将产生以下输出-
{ "_id" : 1, "ListOfName" : [ "John", "Robert", "David" ] } { "_id" : 2, "ListOfName" : [ "Mike", "Sam" ] } { "_id" : 3, "ListOfName" : [ "John", "David", "Bob" ] }
以下是获取文档的查询-
> db.demo661.find({"ListOfName": {"$all":["John","David"]}});
这将产生以下输出-
{ "_id" : 1, "ListOfName" : [ "John", "Robert", "David" ] } { "_id" : 3, "ListOfName" : [ "John", "David", "Bob" ] }