如何使用 Mongo 返回具有已篩選子文件的文件?
為此,請在 MongoDB 中使用 $project。在其內部,使用 $filter。讓我們建立一個帶有文件的集合 -
> db.demo457.insertOne(
... {
... _id: 101,
... details: [
... { ProductName:"Product-1" , ProductPrice:90 },
... { ProductName:"Product-2" , ProductPrice:190 }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
>
> db.demo457.insertOne(
... {
... _id: 102,
... details: [
... { ProductName:"Product-3" , ProductPrice:150},
... { ProductName:"Product-4" , ProductPrice:360 }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 102 }使用 find() 方法顯示集合中的所有文件 −
> db.demo457.find();
這將產生以下輸出 −
{ "_id" : 101, "details" : [ { "ProductName" : "Product-1", "ProductPrice" : 90 }, { "ProductName"
: "Product-2", "ProductPrice" : 190 } ] }
{ "_id" : 102, "details" : [ { "ProductName" : "Product-3", "ProductPrice" : 150 }, {
"ProductName" : "Product-4", "ProductPrice" : 360 } ] }以下是使用 MongoDB 返回具有已篩選子文件的文件的查詢 −
> db.demo457.aggregate([
... {
... $project: {
... details: {
... $filter: {
... input: "$details",
... as: "output",
... cond: { $gte: [ "$$output.ProductPrice", 170 ] }
... }
... }
... }
... }
... ])這將產生以下輸出 −
{ "_id" : 101, "details" : [ { "ProductName" : "Product-2", "ProductPrice" : 190 } ] }
{ "_id" : 102, "details" : [ { "ProductName" : "Product-4", "ProductPrice" : 360 } ] }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP