1

I want to modify my mongodb collection from 2d to 2dsphere. I have this structure in my db.users:

{
  "_id" : "1c6930387123e960eecd65e8ade28488",
  "interests" : [
     {
       "_id" : ObjectId("56a8b2a72f2c2a4c0250e896"),
       "coordinates" : [-3.6833, 40.4]
    }
  ],   
}

I would like to have something like this:

{
  "_id" : "1c6930387123e960eecd65e8ade28488",
  "interests" : [
     {
       "_id" : ObjectId("56a8b2a72f2c2a4c0250e896"),
       "loc":{
         "type":"Point",
         "coordinates" : [-3.6833, 40.4]
       }
    }
  ],   
}

I tried this:

db.users.update( {interests:{$elemMatch:{coordinates :  { $exists: true } }}}, { $set: { 'interests.$.place':{"type":"Point", "coordinates":'interests.$.coordinates'} } }, { upsert: false, multi: false });

Obviously, it insert literally "'interests.$.coordinates'

And tried this in Node:

users.find({interests:{$elemMatch:
    {coordinates :  
        { $exists: true } }}} ,
    {"interests.coordinates":1,"interests._id":1,"_id":0 }).forEach( function( doc ){
        users.update( {interests:
            {$elemMatch:
                {_id :  doc.interests[0]['_id'] }}}, 
            { $set: { 'interests.$.loc':{"type":"Point", "coordinates":doc.interests[0]['coordinates']} } }, 
            { upsert: false, multi: false },function(err, numberAffected, rawResponse) {
            var modified=numberAffected.result.nModified;
             console.log(modified)
        });
    });

But coordinates were inserted with mixed values.

Thoughts?

Thanks!!

1 Answers1

0

I didn't test this piece of code but I think this would shed light on this issue.

users.find(
    {interests:{ $elemMatch: {coordinates : { $exists: true } }}}).forEach( function( doc ){

        for(var c = 0; c < doc.interests.length; c++) {

            var orig = doc.interests[c].coordinates;
            doc.interests[c].loc: { type:"Point", coordinates: orig };
            //delete doc.interests[c].coordinates;

        };

        users.update({ _id: doc._id }, doc);
    });

Try to iterate over all documents in your collection modifying the whole document and then update it in a single line.

Warning: If you have a huge quantity of documents in your collection that match the 'find' condition, you should use pagination (skip/limit) to avoid performance and memory issues in the first load.

Findemor
  • 16
  • 3