如何使用 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