首先让我们创建一个包含文档的集合-
> db.searchAnArrayDemo.insertOne({_id:1,"TechnicalDetails":[{"Language":"MongoDB"}]}); { "acknowledged" : true, "insertedId" : 1 } > db.searchAnArrayDemo.insertOne({_id:2,"TechnicalDetails":[{"Language":"MySQL"}]}); { "acknowledged" : true, "insertedId" : 2 } > db.searchAnArrayDemo.insertOne({_id:3,"TechnicalDetails":[{"Language":"MongoDB"}]}); { "acknowledged" : true, "insertedId" : 3 } > db.searchAnArrayDemo.insertOne({_id:4,"TechnicalDetails":[{"Language":"MongoDB"}]}); { "acknowledged" : true, "insertedId" : 4 } > db.searchAnArrayDemo.insertOne({_id:5,"TechnicalDetails":[{"Language":"Java"}]}); { "acknowledged" : true, "insertedId" : 5 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.searchAnArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : 1, "TechnicalDetails" : [ { "Language" : "MongoDB" } ] } { "_id" : 2, "TechnicalDetails" : [ { "Language" : "MySQL" } ] } { "_id" : 3, "TechnicalDetails" : [ { "Language" : "MongoDB" } ] } { "_id" : 4, "TechnicalDetails" : [ { "Language" : "MongoDB" } ] } { "_id" : 5, "TechnicalDetails" : [ { "Language" : "Java" } ] }
以下是搜索哈希数组的查询-
> db.searchAnArrayDemo.find({'TechnicalDetails.Language':'MongoDB'}).count();
这将产生以下输出-
3