MongoDB查询以将文档数组中的每个元素与条件匹配?
您可以every()
在MongoDB中使用它。让我们创建一个包含文档的集合-
> db.arrayConditionDemo.insertOne({"Name":"John","Marks":[40,43,45]}); { "acknowledged" : true, "insertedId" : ObjectId("5cbdbd06de8cc557214c0e1a") } > db.arrayConditionDemo.insertOne({"Name":"Mike","Marks":[45]}); { "acknowledged" : true, "insertedId" : ObjectId("5cbdbd17de8cc557214c0e1b") } > db.arrayConditionDemo.insertOne({"Name":"Chris","Marks":[43,45,59,69,78,89]}); { "acknowledged" : true, "insertedId" : ObjectId("5cbdbd3cde8cc557214c0e1c") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.arrayConditionDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cbdbd06de8cc557214c0e1a"), "Name" : "John", "Marks" : [ 40, 43, 45 ] } { "_id" : ObjectId("5cbdbd17de8cc557214c0e1b"), "Name" : "Mike", "Marks" : [ 45 ] } { "_id" : ObjectId("5cbdbd3cde8cc557214c0e1c"), "Name" : "Chris", "Marks" : [ 43, 45, 59, 69, 78, 89 ] }
以下是将文档数组中的每个元素与条件匹配的查询-
> db.arrayConditionDemo.find("return this.Marks.every(function(m) { return (m >= 40 && m<= 100) })");
这将产生以下输出-
{ "_id" : ObjectId("5cbdbd06de8cc557214c0e1a"), "Name" : "John", "Marks" : [ 40, 43, 45 ] } { "_id" : ObjectId("5cbdbd17de8cc557214c0e1b"), "Name" : "Mike", "Marks" : [ 45 ] } { "_id" : ObjectId("5cbdbd3cde8cc557214c0e1c"), "Name" : "Chris", "Marks" : [ 43, 45, 59, 69, 78, 89 ] }