让我们看一个示例并创建包含文档的集合-
> 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 } ] }