简体   繁体   English

MongoDB 和 nodejs,通过 id 列表查找

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

I have two collections: users:我有两个集合:用户:

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

docs:文档:

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

I want to get docs from ids.我想从 ids 获取文档。 I try this solution , but I get this message:我尝试了这个解决方案,但我收到了这条消息:

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

Your message looks like a mongodb cursor returned from find by native mongodb driver .您的消息看起来像是由本机 mongodb 驱动程序从 find 返回的mongodb 游标

To get actual data you should use toArray function of the cursor:要获取实际数据,您应该使用游标的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);
});

But I recommend you to switch from native mongodb driver to some wrapper around it like monk .但我建议您从原生 mongodb 驱动程序切换到它周围的一些包装器,如Monk

If you care about the order of the list, the answer of Mr.Leonid may not work as expected to do.如果您关心列表的顺序,Leonid 先生的回答可能不会按预期工作。

That's because find gets the docs that have _id equals to any _ids $in the list so the output docs will be ordered by the main order of the collection itself not the order of the input list.那是因为find获取具有 _id 等于列表中任何 _ids $in的文档,因此输出文档将按集合本身的主顺序而不是输入列表的顺序进行排序。

To solve that you can just use the normal findOne with a for loop to the list.为了解决这个问题,你可以使用普通的findOne和一个 for 循环到列表。

The code will look like:代码将如下所示:

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