简体   繁体   English

仅从 mongoose 中的文档返回一个子文档

[英]Return only a subdocument from document in mongoose

I am working on an app that uses MongoDB (I use Mongoose) as its database.我正在开发一个使用 MongoDB(我使用 Mongoose)作为其数据库的应用程序。

I have a question, suppose I have this kind of schema:我有一个问题,假设我有这种模式:

 [{ "user_id":"2328292073" "username":"Bob", "subscriptions":[ { "id":"38271281, "payments":[ { "id":"00001", "amount":"1900" }, { "id":"00002", "amount":"2000" }, { "id":"00003", "amount":"3000" } ] } ] }]

In my case I want to get the payments array for subscription with id = '38271281' of user with id '2328292073', but I just want to retrieve the payment array, nothing else在我的例子中,我想获取 ID 为“2328292073”的用户的 ID =“38271281”的订阅付款数组,但我只想检索付款数组,没有别的

My query is the following:我的查询如下:

 Mongoose.findOne({ "user_id": "2328292073", "subscriptions.id": "38271281" }, { "subscriptions.payments": 1 })

But I get the entire document of subscriptions.但是我得到了整个订阅文档。 How can i get the payment array only?我怎样才能只获得付款数组?

you can try using unwind if you want filteration from db only.如果您只想从数据库中过滤,可以尝试使用 unwind。


Mongoose.aggregate([
  {
    '$match': {
      'user_id': '2328292093'
    }
  }, {
    '$unwind': {
      'path': '$subscriptions'
    }
  }, {
    '$match': {
      'subscriptions.id': '38271281'
    }
  }
])

if you will have multiple documents having same subscription id then you have to group it.如果您将有多个具有相同订阅 ID 的文档,那么您必须将其分组。

  • using code level filter function can also be one another approach to do this.使用代码级过滤器 function 也可以是另一种方法来做到这一点。

You can try aggregation operators in projection in find method or also use aggregation method,您可以在 find 方法的投影中尝试聚合运算符,也可以使用聚合方法,

  • $reduce to iterate loop of subscriptions and check the condition if id matched then return payment array $reduce迭代subscriptions循环并检查条件是否匹配 id 然后返回支付数组
db.collection.find({
  "user_id": "2328292073",
  "subscriptions.id": "38271281"
},
{
  payments: {
    $reduce: {
      input: "$subscriptions",
      initialValue: [],
      in: {
        $cond: [
          { $eq: ["$$this.id", "38271281"] },
          "$$this.payments",
          "$$value"
        ]
      }
    }
  }
})

Playground操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM