简体   繁体   English

查询 mongodb 以获取集合中所有子文档的数组

[英]Query mongodb for an array of all subdocuments in a collection

I can't seem to find a solution for this.我似乎无法为此找到解决方案。 I have a collection of users, each user has a subdocument array of payments.我有一组用户,每个用户都有一个付款子文档数组。 I want to be able to load all the payments of all users and add them to a table.我希望能够加载所有用户的所有付款并将它们添加到表中。

my schema looks like:我的架构看起来像:

Users: 
 {name: String,
 surname: String,
 payments: [
   {date: Date,
   amount: Number}
]}

I have run the following query in the node console and it returns a list of documents:我在节点控制台中运行了以下查询,它返回了一个文档列表:

var allPayments = Users.find( { "payments.amount": { $exists: true }} );

, but when I add it to my route and console log it, I get a Query{} document with my schema not the list of documents. ,但是当我将它添加到我的路由和控制台记录它时,我得到一个带有我的架构而不是文档列表的 Query{} 文档。 I have tried adding .lean() and.pretty() but they return errors saying they are not functions, same as when I try to run a forEach() (maybe im doing it wrong).我尝试添加.lean() and.pretty()但它们返回错误,说它们不是函数,就像我尝试运行 forEach() 时一样(也许我做错了)。

I have also tried using aggregate as below:我也尝试过使用如下聚合:

var test = Users.aggregate([{$unwind: '$payments'},{$sort: {'payments.date': 1}},{$group: {_id: 0, 'payments': {$push: '$payments'}}}])

and what I get back is:我得到的是:

Aggregate {
  _pipeline:
   [ { '$unwind': '$payments' },
     { '$sort': [Object] },
     { '$group': [Object] } ],
  _model: Model { Users },
  options: {} }

this is my route这是我的路线

router.get('/payments', function(req, res) {

    var allPayments = Users.find({
        "payments.bank": {
            $exists: true
        }
    });

    var test = Users.aggregate([{
        $unwind: '$payments'
    }, {
        $sort: {
            'payments.requestdate': 1
        }
    }, {
        $group: {
            _id: 0,
            'payments': {
                $push: '$payments'
            }
        }
    }])

    console.log(test)
    console.log(allPayments)

});

So I solved the issue by changing my schemas, I basically made payment I to its own schema and then included the user ID into each payment that is created.所以我通过改变我的模式解决了这个问题,我基本上支付了我自己的模式,然后将用户 ID 包含到创建的每个支付中。 Then I just ran a db.然后我只运行了一个数据库。 Collection.收藏。 Find() to load all payments Find() 加载所有付款

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

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