Mongojs从两个集合中提取数据并合并结果

Mongojs fetching data from two collections and merging the result

本文关键字:提取 数据 结果 合并 集合 两个 Mongojs      更新时间:2023-09-26

我是mongodb的新手,非常感谢在下面描述的问题上提供帮助。

我有两个收藏品"用户"answers"包"。用户收集方案具有{username,firstname,lastname},袋子收集方案具有{username,bagname,bagimage}。

在提取用户包时,我还想显示名字和姓氏。我的问题是,我似乎无法正确地构建查询。我使用的是nodejs和mongojs驱动程序。以下是我提取所有行李的查询

  thmConfig.db.bags.find({status: "1"}).sort({$natural:-1}, function(err, data) 
{
        var bagList = '{"bags":[';

     if( err || !data) res.send('[{"status": "0"}]');
        else data.forEach( function(innerData) {
            console.log(innerData.username);
            bagList += JSON.stringify(innerData)+",";
                 /*
                   This is where I would lke to also append the firstname from the 
                users collection
                   */
        });
    console.log(bagList.slice(0,1));
    res.write(magList.slice(0,-1));
    res.end(']}');
});     

我将非常感谢有关这方面的任何帮助或建议。我没有改变驱动程序的选择,所以我现在特别想使用mongojs来实现这一点。

谢谢和问候,Titash

我认为除了从users集合中读取并以编程方式执行此"联接"操作之外,您别无选择。您可以读取每个包的用户文档(在循环中),也可以提前将整个用户集合读取到一个对象中,并通过用户名进行查找

您可以使用$in运算符。

伪代码(ish):

// get an array of bags matching your query
db.bags.find({status: "1"}).sort({$natural:-1}, function(err, bags) {
  // get a list of usernames from the bags:
  var usernames = bags.map(function(bag) { return bag.username; });
  // perform query on user table: find all users for which we have a bag
  db.users.find({ username : { $in : usernames } }, function(err, users) {
    // create a mapping of username -> first name for easy lookup
    var usernames = {};
    users.forEach(function(user) {
      usernames[user.username] = user.firstname;
    });
    // map first names to bags
    bags.forEach(function(bag) {
      bag.firstname = usernames[bag.username];
    });
    // done: return it as JSON (no need to build a JSON string ourselves)
    res.send({ bags : bags });
  });
});