您可以使用find()
方法来查找带有包含特定值的数组的文档。语法如下:
db.yourCollectionName.find({"yourArrayFieldName":"yourValue"},.......N).pretty();
为了理解上述语法,让我们创建一个包含文档的集合。用于创建包含文档的集合的查询如下:
>db.findSpecificValue.insertOne({"StudentId":1,"StudentName":"Larry","FavouriteSubject":["C","C++","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c6e8996140577d89182b8d0") } >db.findSpecificValue.insertOne({"StudentId":2,"StudentName":"Larry","FavouriteSubject":["MongoDB","MySQL","SQL Server"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c6e89b1140577d89182b8d1") }
在find()
method的帮助下显示集合中的所有文档。查询如下:
> db.findSpecificValue.find().pretty();
以下是输出:
{ "_id" : ObjectId("5c6e8996140577d89182b8d0"), "StudentId" : 1, "StudentName" : "Larry", "FavouriteSubject" : [ "C", "C++", "Java" ] } { "_id" : ObjectId("5c6e89b1140577d89182b8d1"), "StudentId" : 2, "StudentName" : "Larry", "FavouriteSubject" : [ "MongoDB", "MySQL", "SQL Server" ] }
这是查询,用于查找包含特定值(即“ MongoDB”)的数组的文档,该数组用于FavouriteSubject:
> db.findSpecificValue.find({"FavouriteSubject":"MongoDB"}).pretty();
以下是输出:
{ "_id" : ObjectId("5c6e89b1140577d89182b8d1"), "StudentId" : 2, "StudentName" : "Larry", "FavouriteSubject" : [ "MongoDB", "MySQL", "SQL Server" ] }