一种方法是简单地使用 runCommand API。
db.runCommand ( { distinct: "distinct", key: "_id" } )
这给了你这样的东西:
{
"values" : [
ObjectId("54cfcf93e2b8994c25077924"),
ObjectId("54d672d819f899c704b21ef4"),
ObjectId("54d6732319f899c704b21ef5"),
ObjectId("54d6732319f899c704b21ef6"),
ObjectId("54d6732319f899c704b21ef7"),
ObjectId("54d6732319f899c704b21ef8"),
ObjectId("54d6732319f899c704b21ef9")
],
"stats" : {
"n" : 7,
"nscanned" : 7,
"nscannedObjects" : 0,
"timems" : 2,
"cursor" : "DistinctCursor"
},
"ok" : 1
}
但是,使用实际的distinct API 还有一个更好的方法:
var ids = db.distinct.distinct('_id', {}, {});
这只是给你一个 id 数组:
[
ObjectId("54cfcf93e2b8994c25077924"),
ObjectId("54d672d819f899c704b21ef4"),
ObjectId("54d6732319f899c704b21ef5"),
ObjectId("54d6732319f899c704b21ef6"),
ObjectId("54d6732319f899c704b21ef7"),
ObjectId("54d6732319f899c704b21ef8"),
ObjectId("54d6732319f899c704b21ef9")
]
不确定第一个版本,但 Node.js 驱动程序肯定支持后者(我看到你提到你想使用它)。看起来像这样:
db.collection('c').distinct('_id', {}, {}, function (err, result) {
// result is your array of ids
})