如何使用查詢和帶有範圍的過濾器在 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