如何使用查询和带有范围的过滤器在 MongoDB 文档中找到特定数组元素?
为此,请在 MongoDB 中使用 aggregate()。让我们创建一个带有文档的集合 −
> 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 } ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP