如何在带有查询的MongoDB文档中找到特定的数组元素,并通过范围进行过滤?
为此,请aggregate()
在MongoDB中使用。让我们创建一个包含文档的集合-
> db.demo351.insertOne( ... { ... ... "_id" : "101", ... "ProductDetails" : [ ... { ... "ProductName" : "Product-1", ... "ProductPrice" :500 ... }, ... { ... "ProductName" : "Product-2", ... "ProductPrice" :400 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : "101" } > db.demo351.insertOne( ... { ... ... "_id" : "102", ... "ProductDetails" : [ ... { ... "ProductName" : "Product-3", ... "ProductPrice" :200 ... }, ... { ... "ProductName" : "Product-4", ... "ProductPrice" :800 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : "102" }
在find()
方法&mnus;的帮助下显示集合中的所有文档。
> db.demo351.find();
这将产生以下输出-
{ "_id" : "101", "ProductDetails" : [ { "ProductName" : "Product-1", "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductPrice" : 400 } ] } { "_id" : "102", "ProductDetails" : [ { "ProductName" : "Product-3", "ProductPrice" : 200 }, { "ProductName" : "Product-4", "ProductPrice" : 800 } ] }
以下是查询以查找带有查询的MongoDB文档中的特定数组元素并使用范围过滤-
> db.demo351.aggregate([ ... { ... $match: { _id: "102" } ... }, ... { ... $addFields: { ... ProductDetails: { ... $filter: { ... input: "$ProductDetails", ... cond: { ... $and: [ ... { $gt: [ "$$this.ProductPrice", 600 ] }, ... { $lt: [ "$$this.ProductPrice", 900 ] } ... ] ... } ... } ... } ... } ... } ... ])
这将产生以下输出-
{ "_id" : "102", "ProductDetails" : [ { "ProductName" : "Product-4", "ProductPrice" : 800 } ] }