如何在 MongoDB 中根据数组中匹配对象的数目查找文档?
我们来看一个例子,创建一个带有文档的集合 -
> db.demo694.insertOne( ... { ... "details" : ... [ ... { ... "Name" : "Chris", ... Age:21 ... }, ... { ... "Name" : "David", ... Age:22 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea59279ece4e5779399c07f") } > db.demo694.insertOne( ... { ... "details" : ... [ ... { ... "Name" : "Bob", ... Age:21 ... }, ... { ... "Name" : "Mike", ... Age:23 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea5927aece4e5779399c080") } > db.demo694.insertOne( ... { ... "details" : ... [ ... { ... "Name" : "Chris", ... Age:21 ... }, ... { ... "Name" : "Carol", ... Age:22 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea5927aece4e5779399c081") }
使用 find() 方法从集合中显示所有文档 -
> db.demo694.find();
这会产生以下输出 -
{ "_id" : ObjectId("5ea59279ece4e5779399c07f"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 22 } ] } { "_id" : ObjectId("5ea5927aece4e5779399c080"), "details" : [ { "Name" : "Bob", "Age" : 21 }, { "Name" : "Mike", "Age" : 23 } ] } { "_id" : ObjectId("5ea5927aece4e5779399c081"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Carol", "Age" : 22 } ] }
以下是根据数组中匹配对象的数目在 MongoDB 中查找文档的查询 -
> nameChrisAge21= function () { ... var inc = 0; ... this.details.forEach(function (d) { ... if (d.Name == "Chris" && d.Age == 21) { ... inc= inc + 1; ... } ... }); ... if (inc >= 1) { ... return true; ... } ... } function () { var inc = 0; this.details.forEach(function (d) { if (d.Name == "Chris" && d.Age == 21) { inc= inc + 1; } }); if (inc >= 1) { return true; } } > db.demo694.find({$where:nameChrisAge21});
这会产生以下输出 -
{ "_id" : ObjectId("5ea59279ece4e5779399c07f"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 22 } ] } { "_id" : ObjectId("5ea5927aece4e5779399c081"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Carol", "Age" : 22 } ] }
广告