首先让我们创建一个包含文档的集合-
> db.findDataDemo.insertOne( { "_id": new ObjectId(), "CustomerName":"John", "CustomerDetails" : { "CountryName" : [ "AUS" ], "isMarried" : [ false ] } } ); { "acknowledged" : true, "insertedId" : ObjectId("5cefa5eeef71edecf6a1f6a5") } > db.findDataDemo.insertOne( { "_id": new ObjectId(), "CustomerName":"Carol", "CustomerDetails" : { "CountryName" : [ "UK" ], "isMarried" : [ true ] } } ); { "acknowledged" : true, "insertedId" : ObjectId("5cefa60aef71edecf6a1f6a6") }
在find()
方法的帮助下显示集合中的所有文档-
> db.findDataDemo.find().pretty();
输出结果
{ "_id" : ObjectId("5cefa5eeef71edecf6a1f6a5"), "CustomerName" : "John", "CustomerDetails" : { "CountryName" : [ "AUS" ], "isMarried" : [ false ] } } { "_id" : ObjectId("5cefa60aef71edecf6a1f6a6"), "CustomerName" : "Carol", "CustomerDetails" : { "CountryName" : [ "UK" ], "isMarried" : [ true ] } }
以下是从对象内部的数组中查找数据的查询-
> db.findDataDemo.find({"CustomerDetails.CountryName":"UK"});
输出结果
{ "_id" : ObjectId("5cefa60aef71edecf6a1f6a6"), "CustomerName" : "Carol", "CustomerDetails" : { "CountryName" : [ "UK" ], "isMarried" : [ true ] } }