在 MongoDB 中的对象数组中查找具有两个特定标识符的所有文档?
对此可以使用 $and 运算符。我们先用文档创建一个集合 -
> db.twoSpecificIdsDemo.insertOne( ... { ... PlayerId:1, ... "PlayerDetails": [{ ... id: 100, ... "PlayerName":"Chris" ... },{ ... id: 101, ... "PlayerName":"Sam" ... },{ ... id: 102, ... "PlayerName":"Robert" ... },{ ... id: 103, ... "PlayerName":"Carol" ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd3e130edc6604c74817ce4") } > db.twoSpecificIdsDemo.insertOne( ... { ... PlayerId:1, ... "PlayerDetails": [{ ... id: 104, ... "PlayerName":"Mike" ... },{ ... id: 105, ... "PlayerName":"Bob" ... },{ ... id: 102, ... "PlayerName":"Ramit" ... },{ ... id: 106, ... "PlayerName":"David" ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd3e167edc6604c74817ce5") }
下面是使用 find() 方法显示集合中所有文档的查询 -
> db.twoSpecificIdsDemo.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cd3e130edc6604c74817ce4"), "PlayerId" : 1, "PlayerDetails" : [ { "id" : 100, "PlayerName" : "Chris" }, { "id" : 101, "PlayerName" : "Sam" }, { "id" : 102, "PlayerName" : "Robert" }, { "id" : 103, "PlayerName" : "Carol" } ] } { "_id" : ObjectId("5cd3e167edc6604c74817ce5"), "PlayerId" : 1, "PlayerDetails" : [ { "id" : 104, "PlayerName" : "Mike" }, { "id" : 105, "PlayerName" : "Bob" }, { "id" : 102, "PlayerName" : "Ramit" }, { "id" : 106, "PlayerName" : "David" } ] }
以下是查询在 MongoDB 中的对象数组中查找具有两个特定标识符的所有文档 -
> db.twoSpecificIdsDemo.find( { $and : [ { "PlayerDetails.id" : 102 }, { "PlayerDetails.id" : 103 } ] } ).pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cd3e130edc6604c74817ce4"), "PlayerId" : 1, "PlayerDetails" : [ { "id" : 100, "PlayerName" : "Chris" }, { "id" : 101, "PlayerName" : "Sam" }, { "id" : 102, "PlayerName" : "Robert" }, { "id" : 103, "PlayerName" : "Carol" } ] }
广告