我有以下收藏
[ { _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' } }} ])但是它给了我这样的输出
But it gives me output like this
[ { _id: null, category: [ 'Breakfast', 'Brunch', 'Lunch' ] } ]我想要这样的输出
[ 'Breakfast', 'Brunch', 'Lunch' ]推荐答案
您可以map().将 Array.map() 与猫鼬一起使用因为它返回一个数组,所以最好使用 $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.
更多推荐
仅以值数组形式返回结果
发布评论