Home > Back-end >  Get multiple documents from collection using nodejs and mongodb
Get multiple documents from collection using nodejs and mongodb

Time:11-22

Hi I have two mongodb collections. The first one returns json data (array) and with the output of this, I want to return documents that match.

When I run Console.log (req.bidder.myBids) I get the following output:

 [{"productId":"3798b537-9c7b-4395-9e41-fd0ba39aa984","price":3010},{"productId":"3798b537-9c7b-4395-9e41-fd0ba39aa984","price":3020},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1040},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1050},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1060},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1070},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1090},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1100}]

The productId has duplicates, I want to remove duplicates and then call a routine that finds all the products that match and output as json. So far I have this code that only outputs one document, but cant figure out how to add the array of productId's and then fetch all corresponding products.

     var agencyId = req.body.agencyId;
    var productId = req.body.productId;
   

    if (!validate.STRING(agencyId)) {
        res.apiError(messages.server.invalid_request);

    } else {

        dbProduct.find({productId:{$in:['3798b537-9c7b-4395-9e41-fd0ba39aa984','4c4bd71c-6664-4d56-b5d3-6428fe1bed19']}
            
           
        }).then(dbRes => { 
        

console.log(dbRes);

Updated code and works with hard-wired productId and updated above code. Looking at how to get the array data and transpose replacing the hard-wired productId's

CodePudding user response:

The $in operator is what you want. See the docs here: https://docs.mongodb.com/manual/reference/operator/query/in/

  • Related