简体   繁体   中英

Checking if value exists across multiple documents and returning that document

Say I have the following documents in a MongoDB collection:

{
   "recipeName": "barbecued chicken",
   "author_id": "123"
}
{
   "recipeName": "grilled steak",
   "author_id": "123"
}
{
   "recipeName": "pork and beans",
   "author_id": "444"
}
{
   "recipeName": "gravy",
   "author_id": "333"
}
{
   "recipeName": "corn chowder",
   "author_id": "222"
}
{
   "recipeName": "pork roast",
   "author_id": "543"
}

Then, I have this array in javascript:

["grilled steak", "baked steak", "smothered steak"]

I want to see if any value from my array matches the recipeName of any document(in this case, grilled steak would match). Then, I want to get the author_id for the matched document.

I realize I could query recipeName for each item in the array, but is there a more efficient way of doing this? This array could be large(which would be a lot of queries). Can I check for all of the items in my array at once and if I get a match get the author_id returned to me?

This is just an example, not the actual data :P. Thanks in advance for any suggestions.

I currently have this in a loop, but am looking for a more efficient way...

   mongo.connect(uristring, function (err, db) {
      db.collection("recipes", function(err, collection) {
         if (!err) {
            collection.findOne({
               'recipeName': recipeName
            }, function (err, href) {
               if (err) {
                  return false;
               }
               if (!href) {
                  return false;
               }
               return true;
            });
         } else {
            console.log(5, 'DB error');
         }
      });
   });

You can use the $in operator for that:

collection.findOne({
   recipeName: { $in: ["grilled steak", "baked steak", "smothered steak"] }
}, function (err, href) { ... });

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