且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Node.js:如何在查询聚合中返回对象?

更新时间:2022-05-31 05:41:14

正式地,聚合命令将管道参数的列表"作为其主要输入.这就是为什么首选"Array"语法的原因.尽管您似乎使用的猫鼬方法并未严格实施此方法,但这种情况很可能会改变.

Officially, the aggregate command takes a "list" of pipeline arguments as it's main input. This is why the "Array" syntax is preferred. Though it is not strictly implemented this way by the mongoose method you appear to be using, this is likely to change.

正式"参数为

  1. 表示管道条件的数组

  1. An array representing the pipeline conditions

一个选项文档,其中指定了用于更改行为的各种选项.

An options document specifying various options to alter the behavior.

因此,这里的猫鼬表单只是在查找列表"中的哪个项是function(),并事先将所有内容视为管道.但这在将来必须改变.但是,您的问题似乎更多是关于期望"不同的形式以生成文档"或数组"作为响应.但这不会发生.

So the mongoose form here is just looking for which item in the "list" is a function() and considers everything beforehand to be pipeline. But this will have to change in the future. Your question though seems to be more about "expecting" the different form to produce either a "document" or an "array" in response. But this will not happen.

您并非如此,这是有充分理由的.聚合框架可以像 $project 或其他组"信息,例如 $group .

You don't really and there is a good reason why. The aggregation framework either performs manipulation on collection content just as with $project or otherwise "groups" information such as with $group.

通常只希望返回一个"结果的唯一方法是当您明确地 $match 仅获得一个结果,否则/ > $limit 对一个或什至您的 $group 的值是单数或null值的响应.

The only ways in which you generally expect only "one" result to return is when you either specifically $match to obtain only one result or otherwise $limit the response to one or even if your $group is on a singular or null value.

通常期望它是结果的集合"或在这里表示为数组.实际上,现代的MongoDB服务器和驱动程序实现可以返回游标",因此结果可能大于使用新版本的16MB BSON限制.但基本上还是一个列表.

It is generally expected to be a "collection" of results or here represented as an array. Modern MongoDB servers and driver implementations can in fact return a "cursor", so the results can be larger than the 16MB BSON limit with newer versions. But still basically a list.

因此,它始终是一个数组,看起来像您正在使用的猫鼬"之类的东西.只需返回第一个元素"即可.甚至可能限制为1:

So it's always an array at present with something like "mongoose", which it looks like you are using. Just return the "first element" when it is all you want. Possibly even limit to 1 as well:

MyModel.aggregate(
  [
    { "$match": ... },
    { "$group": ... },
    { "$limit": 1 }
  ], function(err, result) {
      console.log(result[0]);
});

无论哪种方法,基本上都是像.findOne()这样的方法.

Which is essentially all that methods like .findOne() are doing under the covers anyway.