使用 MongoDB 从数组中一部分对象进行查询
要从数组中部分对象进行查询,请使用 $findOne() 和 $all。我们先创建一个包含文档的集合 -
> db.demo25.insertOne( ... { ... ... "Details":[ ... { ... "UserId":"Carol101", ... "UserName":"Carol" ... }, ... { ... "UserId":"David102", ... "UserName":"David" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e14c86e22d07d3b95082e77") } > db.demo25.insertOne( ... { ... ... "Details":[ ... { ... "UserId":"Chris101", ... "UserName":"Chris" ... }, ... { ... "UserId":"Mike102", ... "UserName":"Mike" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e14c86f22d07d3b95082e78") }
在 find() 方法的帮助下从集合中显示所有文档 -
> db.demo25.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e14c86e22d07d3b95082e77"), "Details" : [ { "UserId" : "Carol101", "UserName" : "Carol" }, { "UserId" : "David102", "UserName" : "David" } ] } { "_id" : ObjectId("5e14c86f22d07d3b95082e78"), "Details" : [ { "UserId" : "Chris101", "UserName" : "Chris" }, { "UserId" : "Mike102", "UserName" : "Mike" } ] }
以下是如何从数组中部分对象进行查询 -
> db.demo25.findOne({ "Details.UserId":{$all : ["Carol101","David102"]}});
这将产生以下输出 -
{ "_id" : ObjectId("5e14c86e22d07d3b95082e77"), "Details" : [ { "UserId" : "Carol101", "UserName" : "Carol" }, { "UserId" : "David102", "UserName" : "David" } ] }
广告