简体   繁体   English

使用聚合 MongoDB

[英]using aggregation MongoDB

I'm trying to use .aggregate() with other mongo shell methods and i got UnhandledPromiseRejectionWarning: TypeError: User.find(...).select(...).sort(...).aggregate is not a function我正在尝试将 .aggregate() 与其他 mongo shell 方法一起使用,但我得到了UnhandledPromiseRejectionWarning: TypeError: User.find(...).select(...).sort(...).aggregate is not a function

const users = await User
            .find(findParams)
            .select(userResponse)
            .sort(sortParams)
            .aggregate(([
                {
                    $project:{
                        dateCreated: {$dateToString: {format: "%G-%m-%d %H:%M:%S", date: "$dateCreated"}},
                    }
                }
            ]))
            .exec()

BUT, when i use .aggregate() without other methods it works perfect.但是,当我在没有其他方法的情况下使用 .aggregate() 时,它工作得很好。

const users = await User
            .aggregate(([
                {
                    $project:{
                        dateCreated: {$dateToString: {format: "%G-%m-%d %H:%M:%S", date: "$dateCreated"}},
                    }
                }
            ]))
            .exec()

Can i insert it with other methods but without getting this error.我可以用其他方法插入它,但不会出现此错误。 Thanks谢谢

In the first block of code, you are trying to apply db.collection.aggregate() method on a cursor which is returned by find() method.在第一个代码块中,您尝试在 find() 方法返回的游标上应用 db.collection.aggregate() 方法。 Cursors are which basically returned from collection methods like find(), aggregate() andmore here .游标基本上从收集方法返回象find()方法,骨料()和更多在这里

In the second code block, you are directly applying aggregate() on the User collection.在第二个代码块中,您直接在User集合上应用了aggregate()。 That's why it is working.这就是它起作用的原因。 And yes, you can do whatever select, sort, limit using aggregate() even without using those cursor methods here .是的,即使不使用此处的游标方法,您也可以使用 aggregate() 进行任何选择、排序和限制。 Hope this will help, Dude.希望这会有所帮助,伙计。 Have a great day!祝你有美好的一天!

MongoDB documentation page screenshot MongoDB 文档页面截图

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

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