且构网

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

仅以值数组形式返回结果

更新时间:2023-12-05 22:53:40

您可以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.