2

I need to create a new field from a substring (two characters string) of another field in MongoDB. Help me, please.

Example:

field1  field2
abcdef  ab
qwerty  qw
opuytj  op

My code:

db.mycollection.update({}, {$set : {"field2": { $substr: [ {"field1"}, 0, 2 ] } }},
                        {upsert:false, multi:true}) 

2 Answers2

3

if you have mongodb server v4.2 or newer you can do it easily like so:

db.mycollection.updateMany({}, [
    {
        "$set": {
            "field2": {
                "$substr": ["$field1", 0, 2]
            }
        }
    }
])

the above was generated using the following c# code:

using MongoDB.Entities;
using MongoDB.Entities.Core;

namespace StackOverflow
{
    public class Item : Entity
    {
        public string field1 { get; set; }
    }

    public class Program
    {
        private static void Main()
        {
            new DB("test", "localhost");

            (new[] {
              new  Item {field1 = "abcdef"},
              new  Item {field1 = "qwerty"},
              new  Item {field1 = "opuytj"}
            }).Save();

            DB.Update<Item>()
              .Match(_ => true)
              .WithPipelineStage("{$set : { field2 : { $substr: [ '$field1', 0, 2 ] } }}")
              .ExecutePipeline();
        }
    }
}
Dĵ ΝιΓΞΗΛψΚ
  • 5,068
  • 3
  • 13
  • 26
0

Please use find with forEach keyword

db.demo.find({}).forEach( function(myDoc) { 
    var condname=myDoc.name;
    var condcat=myDoc.category;
    var replaceName =condcat.substring(0,2);

   db.demo.update({_id: myDoc._id}, {$set : {"name": replaceName }},
                        {upsert:false, multi:true}) 

} );
Mahesh Bhatnagar
  • 1,042
  • 1
  • 7
  • 8