Mongoose - 获取 _ids 列表而不是具有 _id 的对象数组

问题描述 投票:0回答:2

我想运行以下查询:

Group.find({program: {$in: [...]}}).lean().select('_id')

然后得到以下反馈:

[{_id: ...}, {_id: ...}, {_id: ...}, {_id: ...}]

但是以下:

[..., ..., ..., ...] where ... represents an _id of a Group

当然,我可以只运行查询,然后循环遍历我返回的组,但如果可能的话,我想在查询中执行此操作,因为这可能会更快。

谢谢大家!

node.js mongodb mongoose
2个回答
56
投票
Group.find({program: {$in: [...]}})
  .distinct('_id')

db.collection.distinct(字段,查询)

在单个集合中查找指定字段的不同值并以数组形式返回结果。

了解更多


0
投票

您还可以将查询直接传递到

distinct()
调用中:

Group.distinct('_id', {program: {$in: [...]}})

这将返回满足查询的 ObjectId 数组。

© www.soinside.com 2019 - 2024. All rights reserved.