仅将结果作为值数组返回 [英] Return result as an Array of Values Only
问题描述
我有以下收藏
[ { _id: 5b12a7977990062f097d03ce,
name: 'Breakfast',
category: 'dining' },
{ _id: 5b12a7977990062f097d03d0,
name: 'Brunch',
category: 'dining' },
{ _id: 5b12a7977990062f097d03d2,
name: 'Lunch',
category: 'dining' } ]
我必须在主数组中收集所有具有 category
dining
的 name
I have to collect all the name
having category
dining
in a main array
我已经试过了
const subCategory = await SubCategory.aggregate([
{ '$match': { category: "dining" }},
{ '$group': {
'_id': null,
'category': { '$push': '$name' }
}}
])
但它给了我这样的输出
[ { _id: null,
category:
[ 'Breakfast',
'Brunch',
'Lunch' ] } ]
我想要这样的输出
[ 'Breakfast',
'Brunch',
'Lunch' ]
推荐答案
您可以map()
.使用 Array.map()
使用 mongoose,因为它返回一个数组,您最好只使用 $group
_id
比使用 $push
You can map()
. Use Array.map()
with mongoose as it returns an array, and you are better off simply using the $group
_id
than using $push
const subCategory = (await SubCategory.aggregate([
{ '$match': { category: "dining" } },
{ '$group': { '_id': "$name" } }
])).map(({ _id }) => _id);
或者使用 Cursor.map()
如果使用来自核心驱动程序的底层 Collection
:
const subCategory = await SubCategory.collection.aggregate([
{ '$match': { category: "dining" } },
{ '$group': { '_id': "$name" } }
]).map(({ _id }) => _id).toArray();
如果您不想要不同"的结果,则与 find()
大致相同:
Much the same with find()
if you don't want the "distinct" results:
const subCategory = (await Subcategory.find({ category: "dining" }))
.map(({ name }) => name);
或者使用 Cursor.map()
const subCategory = await Subcategory.collection.find({ category: "dining" })
.map(({ name }) => name).toArray();
您也可以使用 distinct()
,它基本上对聚合过程和 map()
幕后"(仅返回字段部分"而不是不同的聚合方法)进行了变体:
You can also use distinct()
, which basically does a variation of the aggregation process and the map()
"under the hood" ( the "return just the field part" and not the distinct aggregation method ):
const subCategory = await SubCategory.distinct("name",{ category: "dining" });
MongoDB 本身不会返回 BSON 文档以外的任何内容,并且一个简单的字符串不是 BSON 文档.
MongoDB itself won't return anything other than a BSON Document, and a simple string is NOT a BSON Document.
这篇关于仅将结果作为值数组返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!