3

I want to run below mongo query from C#. Currently I am using mongodb C# driver 2.7

db.changelog.find({}).forEach(function(doc){
//make javascript object dynimacally 
var newDoc = {
    "key": "value",
    "doc": doc
}
db.changelog_log.insertOne(newDoc); })

This is successfully run into mongo shell, now I want to execute that script from c# application with modify object value dynamically. I was hoping it would be able to parse those queries and pass them off to database.RunCommand but I have not been able to make any progress.

var bsonDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("query");

database.RunCommand(command);

That code fails on the call to Deserialize with this error message: [Additional information: JSON reader was expecting a value but found 'db'.] which makes perfect sense because the script is not valid JSON.

After mongo 3.0 eval function has been depreciated.

So I'm having trouble parsing the script into something that can be executed.

0

1 Answer 1

0

VehicleModel is a model which I am using for inserting and same for retrieving,

so it replaces with your model

        var collection = database.GetCollection<VehicleModel>("VehicleModel");

        var Data = await collection.Find(Builders<VehicleModel>.Filter.Empty).ToListAsync();


        foreach(VehicleModel vm in Data)
        {
            var newDoc =
            {
            "key": "value",
            "doc": vm
            collection.InsertOneAsync(value);
            }
        }

Maybe you are looking for this

Sign up to request clarification or add additional context in comments.

7 Comments

This utility will be used in whole application on all insert, update and delete operation on any collection so through c# foreach loop insert one document at a time have performance issue. So I want to use mongo foreach which will be used on mongo server so application only communicate one time with db server on one request
whenever you add data in mongo they need to go to mongo server always @AdnanAhmedAnsari
Yes you are right, but during loop every time application will be open new connection and application communicate multiple time with database which will be impact on application performance. But on a single request it will perform faster than that logic
ok, you added a c# tag so I thought you need same code in c# but actually, you need code which we can run on mongo shell right?? @AdnanAhmedAnsari
you need to run shell script for that find the link in my updated answer @AdnanAhmedAnsari
|

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.