1

I'm new to Mongo and trying compare a array with a documents of collections and return list of matching records.

Let me explain:First Array

I have a collection (user) with following documents:

> db.user.find().pretty()
{
    "_id" : ObjectId("57358220bf3e7d076b6ccdb1"),
    "name" : "Sunny",
    "phone" : "9417702107",
    "email" : "[email protected]"
}
{
    "_id" : ObjectId("57358242bf3e7d076b6ccdb2"),
    "name" : "Pal",
    "phone" : "9015719419",
    "email" : "[email protected]"
}
{
    "_id" : ObjectId("57358262bf3e7d076b6ccdb3"),
    "name" : "viveky",
    "phone" : "8826565107",
    "email" : "[email protected]"
}

Second Array: i have a array of objects that is come from Http request below is structure of array.

{
 "contacts" : [
            {
                    "name" : "Sunny",
                    "phone" : "9417702107"
            },
            {
                    "name" : "Sukhpal",
                    "phone" : "9015719419"
            },
            {
                    "name" : "anurag",
                    "phone" : "9988776655"
            },
            {
                    "name" : "vivek",
                    "phone" : "8826565107"
            }
         ]
} 

Now I want to know which objects of Second Array are exists in First Array and which doesn't . Comparison should on basis of phone only . And in result i want same Array as Second Array but with one extra field that is "exists":"true" or "exists":"false" . Something like this.

{
   "contacts" : [
            {
                    "name" : "Sunny",
                    "phone" : "9417702107"
                    "exists" :"true"
            },
            {
                    "name" : "pal",
                    "phone" : "90177668899"
                    "exists" :"false"
            }
          ]
  }

So for this i had tried something here is code of node.js with mongoos.

exports.matchcontacts = function(req, res, next)
{
  var response = {};   
  var conArray = req.body.contacts;
  var contact_list = [];

for(var i=0; i<conArray.length;i++)
{  
  var name = conArray[i].name;
  var phone = conArray[i].phone;

  Users.findOne({"phone":conArray[i].phone},function(err,data)
  {
        if(err) 
        {
            response = {"error" : true,"message" : "Error fetching data"};
        } 
        else if(!data)
          {
               contact_list.push({name:name,phone:phone,exists:"false"});
          }
        else 
         {
             contact_list.push({name:name,phone:phone,exists:"true"});
         }

    });
  }
  response = {"error":false,"contacts":contact_list};
  res.json(response);
};

But always got null {} empty result, and if i tried to get response inside Callback function then it return only single last compared value. Problem is in first method is that callback function return result very late so result always empty . and in second method loop override result and it also inefficient to use callback inside loop it will call no of time. So whole story i had explained

Now Please can anybody help me with code or suggest right way to get desired result thanks

8
  • Never used mongodb, but can´t you make an array of phones, search in your db all those phones (Users.find I believe) and process all at once? That way you only have to manage one callback Commented May 13, 2016 at 17:41
  • @juvian i appreciate your suggestion , and i had tried this using $in operator , but it returns all matching result (whole document data) . but how can know which records not found and prepare Array with exists field. and one thing more (User Collection) "name" vale and Second Array "name" field value can be different. so i want name value same as Second Array not from DB. Commented May 13, 2016 at 18:01
  • Array.prototype.findIndex() and Array.prototype.find() are your friends in this quest. Commented May 13, 2016 at 18:09
  • @juvian Actually User Collection is records of registered users, and Contact Array use as second array is Contacts List of user Mobile Phone , My work is just match Users Mobile Contact List with Registered users and return same as Contact List with exists field to inform that exist in DB or not. Commented May 13, 2016 at 18:10
  • Can I assume phones are unique? Commented May 13, 2016 at 18:13

1 Answer 1

1

Haven´t used mongodb, but the idea I would use is to first iterate your contacts and make a mapping of the phones to the corresponding object and mark them as non existent:

var obj = {};

for(var i=0; i<conArray.length;i++){
    obj[conArray[i].phone] = conArray[i];
    conArray[i].exists = false;
}

Then search in some way for the users that have those phones in your db, something like

var results = Users.find(records that have phone in Object.keys(obj) array)

Finally, you iterate your existant records and mark the corresponding contact

for(var i=0;i<results.length;i++){
    obj[results[i].phone].exists = true;
}
Sign up to request clarification or add additional context in comments.

5 Comments

i got idea how to add exists field , but i can't use "name" value from User.find() result.
@SunnyDhiman what do you mean? Why would you need the name value? Thought it was already on contacts
Yes you right Contacts Array Already contain "name" field, but the result that i will got after User.find() contain "name" value different not same as Contacts Array. that's way i can't use. and not return only "phone" Field in Array.
I am only using the phone from the results of user.find there, not using the name at all. Obj will have the names from contacts, the phones and if the phone exists or not in your db. You don´t return results, you return obj
THANKS A LOT JUVIAN

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.