繁体   English   中英

MongoDB 和 nodejs,通过 id 列表查找

[英]MongoDB and nodejs, find throught list of ids

我有两个集合:用户:

{
  _id: ObjectId('123...'),
  docs: [
    ObjectId('512d5793abb900bf3e000002'),
    ObjectId('512d5793abb900bf3e000001')
  ]
}

文档:

{
  _id: ObjectId('512d5793abb900bf3e000002'),
  name: 'qwe',
  ...
}
{
  _id: ObjectId('512d5793abb900bf3e000001'),
  name: 'qwe2',
  ...
}

我想从 ids 获取文档。 我尝试了这个解决方案,但我收到了这条消息:

{ db: { domain: null, _events: {}, _maxListeners: 10, databaseName: 'test', ...

您的消息看起来像是由本机 mongodb 驱动程序从 find 返回的mongodb 游标

要获取实际数据,您应该使用游标的toArray函数:

var ObjectID = require('mongodb').ObjectID;
// you shall wrap each id in ObjectID
var idsProjects = [
  ObjectID('512d5793abb900bf3e000002'),
  ObjectID('512d5793abb900bf3e000001')
];
collectionProjects.find({
  _id: { $in: idsProjects }
},{
  _id: -1, // use -1 to skip a field
  name: 1
}).toArray(function (err, docs) {
  // docs array here contains all queried docs
  if (err) throw err;
  console.log(docs);
});

但我建议您从原生 mongodb 驱动程序切换到它周围的一些包装器,如Monk

如果您关心列表的顺序,Leonid 先生的回答可能不会按预期工作。

那是因为find获取具有 _id 等于列表中任何 _ids $in的文档,因此输出文档将按集合本身的主顺序而不是输入列表的顺序进行排序。

为了解决这个问题,你可以使用普通的findOne和一个 for 循环到列表。

代码将如下所示:

var ObjectID = require('mongodb').ObjectID;
var idsProjects = [
  '512d5793abb900bf3e000002',
  '512d5793abb900bf3e000001'
];
let usersList = new Array();

for (let index = 0; index < idsProjects.length; index++) {
    const myID = idsProjects[index];
    
    const query = { _id: ObjectID(myID) };
    const options = {
    projection: {name: 1 };
    
    var user= await collectionProjects.findOne(query,options);
    
    usersList.push(user);
}

// that's it,
// here we have a list of users 'usersList' 
//with same order of the input ids' list.
console.log(usersList);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM