仅以值数组形式返回结果

编程入门 行业动态 更新时间:2024-10-25 02:26:02
本文介绍了仅以值数组形式返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下收藏

[ { _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.

更多推荐

仅以值数组形式返回结果

本文发布于:2023-10-18 13:21:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504339.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   仅以   形式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!