wazzaday
wazzaday

Reputation: 9664

use variable as key name in mongo db with modifier

I am trying to insert a bunch of arrays into mongoDB.

The data looks something like:

var places = {
    city: ['london', 'york', 'liverpool'],
    country: ['uk', 'france']
};

Each time I add an array, some of the entries could already be there, so I want to ensure there are no duplicates.

db.collection('places').ensureIndex({'city': 1}, {unique: true }, function(){ });
db.collection('places').ensureIndex({'country': 1}, {unique: true }, function(){ });

I then need to loop through the places object and add each item:

for(var key in places){

    db.collection('places').update({_id: 1}, { $addToSet: { key: { $each places[key] } } }, function(err, docs){
        if(err){
            console.log(err);
        }else{
            console.log('success');
        }
    });

}

Here I need key to be the actual keys: 'city', 'country'. Rather than literally being 'key'. But I cant see how this can be achieved with with the modifiers in place.

Upvotes: 1

Views: 2476

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You need to build up your $addToSet value programmatically:

for(var key in places){
    var addToSet = {};
    addToSet[key] = { $each: places[key] };
    db.collection('places').update({_id: 1}, {$addToSet: addToSet}, function(err, docs){
        if(err){
            console.log(err);
        }else{
            console.log('success');
        }
    });
}

But you can do this more efficiently by combining both updates into one:

var addToSet = {};
for(var key in places){
    addToSet[key] = { $each: places[key] };
}
db.collection('places').update({_id: 1}, {$addToSet: addToSet}, function(err, docs){
    if(err){
        console.log(err);
    }else{
        console.log('success');
    }
});

Upvotes: 2

Related Questions