Search code examples
mongodbaggregation-frameworkmongodb-shell

MongoDB - String to ObjectID and create new collection


db.firmalar.find().forEach(function(obj) {
    for( var i = 0; i < obj.osgbIdleri.length; i++){ //ObjectId ARRAY
        obj.osgbIdleri[i] = ObjectId(obj.osgbIdleri[i]);
    }  
  //out:result (firmaId.id & firmaId.osgbIdleri.id(ObjectId))
});

I want to save the string field "obj.osgbIdleri" in each document in the "Firmalar" collection as the ObjectId field. I think I can do this using "aggregation". But when using "aggregation", I can not return every object in foreach. I want to create "firmaId.id" and "firmaId.osgbIdleri.id (ObjectID)" while creating a new collection.


Solution

  • (Posted on behalf of the OP).

    db.firmalar.mapReduce( 
           function() { 
               for( var i = 0; i < this.osgbIdleri.length; i++){
                    this.osgbIdleri[i] = ObjectId(this.osgbIdleri[i]);
                }  
               emit(this._id, this.osgbIdleri); }, 
    
           function(key, values) {return value}, {  
              query:{},  
              out:"firmalarId" 
           }
        ).find()