在一个大的Mongo集合中,如何使用mongoose检索唯一的ID(或任何其他特定的属性)?

假设我有一个Person集合和一个Car集合,并且所有的人都有一辆车,Person文档存储了这个车的Id。

一路上,由于后端validation不好,一些汽车一直坚持数据库,没有任何业主。 我想删除所有这些'孤儿'车。

我的做法可能不是最优化的,但是这里有:

exports.cleanOrphanCars = (req, res) -> Car.find() #find all the cars .exec(err, cars) -> return res.send(StatusMessages.ERROR.code, { error: err }) if err? carIds = cars.map (car) => #map the IDs to a new array for faster iteration return car._id Person.find() .exec(err, people) -> peoplesCarIds = (person) => return person.carId for carId in carIds found = false for personsCarId in peoplesCarIds if personCarId is carId found = true if not found #if no Person references this car, we can remove it Car.remove({_id : carId}) 

获得所有这些CarsPersons是太慢了。 有没有办法直接从mongo获取ID数组,而不必在本地映射ID?

也有可能跳过预取,只有一个查询删除孤儿Cars

使用Person.distinct获取所有人的汽车的_id值的数组,然后用Car.remove $nin删除一个不在该集合中的_id的汽车:

 Person.distinct('carId', function (err, ids) { Car.remove({_id: {$nin: ids}}, function (err) { ... }); });