您可以为此使用$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中的对象数组中查找具有两个特定ID的所有文档的查询-
> 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" } ] }