Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
在某个字段上搜索集合时,我可以指定我只想返回某些字段。在只返回一个字段的情况下,比如说“_id”,find命令返回一个key:value对数组[ {_id:123}, {_id:234}, {_id:345} ] 有没有办法find 只返回一个值数组吗?如:[123、234、345]
我可以自己按摩返回的数组,但如果 mongodb 可以为我做这件事,那么我宁愿让它这样做。
为了获得这种输出,您必须使用聚合框架。即使使用聚合框架,你能得到的最好的还是:
{ values: [ 123, 234, 345 ] }
您基本上必须使用$group来将所有值放在一起。像这样的东西:
$group
db.collectionName.aggregate({ $group: { values: { $push: "$_id" } } });
我不确定你是否需要一个_idfor 组,但如果上述方法不起作用,你可以添加它。我不确定这是否比返回搜索后按摩它更快。
_id