MongoDB汇总函数带有查找功能
我正在使用带有nodejs的coffeescript来查询mongodb数据,但对于某些自定义数据,我需要对我的集合执行聚合函数,但在代码中使用Session.aggregate(query)会给我错误,比如不是管道运算符$and。所以,我在想我们是否可以将聚合函数与 monoogo 的 find 方法集成起来..有什么线索吗?
我在咖啡脚本中定义的查询是:
query = {
$and : [
{ $match : { product: req.body.product } },
{ $project: { "_id": 1, totalHourSpent:{ $subtract: [ "$end_date", "$start_date" ] }}}
]
}
在 mongo shell 中执行时工作正常,但在使用咖啡脚本获取数据时出现错误。
I am using coffeescript with nodejs to query monogodb data but for some custom data i need to perform aggregate function on my collection but using Session.aggregate(query) in the code is giving me error like not pipeline operator $and. So, i was thinking if can we integrate the aggregate func with the find method of monoogo.. any clue?
Query which i have defined in coffee-script is:
query = {
$and : [
{ $match : { product: req.body.product } },
{ $project: { "_id": 1, totalHourSpent:{ $subtract: [ "$end_date", "$start_date" ] }}}
]
}
Working fine while executing in the mongo shell but giving error while fetching the data with the coffee-script.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 MongoDB 聚合语法错误。
它应该是一个数组,而不是传递给
aggregate
方法的对象。mongoose 文档 在示例中显示了这一点,并将您链接到官方 mongo 文档,因为它的语法相同。
您不能使用
$and
作为聚合中的顶级运算符。您可以在$match
运算符内使用它。但您不能使用它来组合$match
和$project
。这是管道中的两个独立步骤,并且按顺序完成。查询中不需要$and
运算符。如果这不起作用,请向我们提供一个包含您的架构的 最小可重现示例,示例文档位于集合、围绕此聚合调用的代码以及发送到服务器的请求数据。
You got the syntax for aggregates in MongoDB wrong.
It should be an array, not an object passed to the
aggregate
method.The mongoose documentation shows this in an example and links you to the official mongo documentation as it's the same syntax.
You cannot use
$and
as a top level operator in an aggregate. You can use it inside a$match
operator. But you cannot use it to combine a$match
and$project
. These are two separate steps in the pipeline and are done in sequence. There is no need for an$and
operator in your query.If this doesn't work, then please provide us with a Minimal Reproducible Example containing your Schema, an example document in the collection, the code surrounding this aggregate call and the request data being sent to the server.
count var 只是为了检查我得到的响应数量,但它总是返回 0。
注意:直接运行时,查询在 Robo3T 中工作正常。
count var just to check the no of response which i get but it returns 0 always.
NOTE: The query is working correctly in the Robo3T when running directly.