从对象内的数组中查找数据的 MongoDB 查询?
我们首先用文档创建一个集合 −
> 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 ] } }
广告