7

I have some documents :

{

    "storeID" : "715R",
    "sensorID" : [ 
        "0BBA", 
        "0BB9"
    ]
}
{

    "storeID" : "312R",
    "sensorID" : [  
        "0BBB"
    ]
}

I want to get result of sensorID which sotreID match any value in storeIDarray like ['715R','312R','789R']

in this case I want get result : a sensorID array : [ "0BBA", "0BB9","0BBB"]

what should I do? thanks.

4
  • $in and then either use a projection or Array.prototype.map Commented Sep 8, 2017 at 8:02
  • 1
    What have you tried so far? Treating peers as a coding service is generally not taken too well. You might want to read How do I ask a good question, which enhances the probability for getting a useful answer drastically. You might find ESR's excellent essay How To Ask Questions The Smart Way helpful. Commented Sep 8, 2017 at 8:25
  • In a document whose storeID matches with the value we are passing as a response you want sensorID's of this storeID .Am I right???? Commented Sep 8, 2017 at 9:30
  • You can use distinct if it suit your needs. db.collection_name.distinct("sensorID", {storeID: {$in: ['715R','312R','789R'] }}) Commented Sep 8, 2017 at 13:08

1 Answer 1

7

You should take a look at the $in operator in MongoDB. Use it with a find, then, to make your request faster, you can use the lean method : with it, mongoDB will return JS objects and not Mongoose model/objects.

YourModel.find({storeID: {$in: storeIDarray }}).lean().exec(yourCallback);

Then, you can use the reduce method on the resulting array :

yourResult.reduce((acc, el) => acc.concat(el.sensorID), []);

Hope it helps,
Best regards

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.