簡體   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