简体   繁体   中英

How can I combine multiple Mongodb queries into one using node.js?

Context:

My database has two collections: "Users" and "Files".

Sample document from "Users" collection:

{
  "username":"Adam",
  "email":"adam@gmail.com",
  "IdFilesOwned":[1,3],
}

As you can see, Adam currently owns two files on the server. Their ids are 1 and 3.

Sample documents from "Files" collection:

{
  "fileId":1,
  "name":"randomPNG.png"
}
{
  "fileId":2,
  "name":"somePDF.pdf"
}
{
  "fileId":3,
  "name":"business.pdf"
}

As you can see, I have three documents on my server, each document having an id and some metadata.

Now, Adam wants to see all the files that he owns, and their metadata. The way i would implement this, is:

1.Lookup the array of file ids that Adam owns.

2.Have node.js run through each id (using a for each loop), and query the metadata for each id.

The problem is that nodejs will make multiple queries (1 query per id). This seems very inefficient. So my question is if there is a better way to implement this?

You can use the $in operator find more info here So it will look something like this.

db.collection('files').find({ fileId: { $in: [<value1>, <value2>, ... <valueN> ] } })

This is more efficent than lookup for sure. Good luck.

I don't have much experience using the driver directly, but you should be able to do the equivalent of the following

db.users.aggregate([
  {
    $lookup: {
      from: "files",
      localField: "IdFilesOwned",
      foreignField: "fileId",
      as: "files"
    }
  }
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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