如何设置 Mongodb 返回文件的限制?

How to set limit on Mongodb returning documents?

我创建了一个 API。我这里有问题。我想将每个文档的 Fields 的限制设置为 return.

API:

const Pipeline = 
          [{
                '$search': {
                    'text': {
                        'query': `${text}`,
                        'path': 'title',
                    }
                }       
          },
          { 
            '$limit': 5 
          }]
var result = await collection.aggregate(pipeline).toArray();
response.status(200).send(result);

我的服务器回复:

  {
    "_id": "039x39sd939hlf",
    "name": "Lorem ipsum dolor sit amet, consectetur adipiscing eli",
    "brand": "Pogoplug",
    "type": "Online data entry",
    "price": 69,
    "description": "giat nulla pariatur. Excepteur sint occa"
  },
  {
    "_id": "039x39sd939hlf",
    "name": "Lorem ipsum dolor sit amet, consectetur adipiscing eli",
    "brand": "Pogoplug",
    "type": "Online data backup",
    "price": 69,
    "description": "giat nulla pariatur. Excepteur sint occa"
  }

现在,我必须这样限制它: 预期结果:

  {
    "name": "Lorem ipsum dolor sit amet, consectetur adipiscing eli",
    "brand": "Peppa Pig",

  },
  {
    "name": "Lorem ipsum dolor sit amet, consectetur adipiscing eli",
    "brand": "Pogoplug",
  },

我应该使用哪种聚合速度快并使之成为可能?

您可以将 $project 阶段仅添加到 return 您想要的字段,如下所示:

const Pipeline = 
[
  {
   /*your current pipeline*/
  },
  {
    "$project": {
      "name": 1,
      "brand": 1
    }
  }
]

示例here