Using MongoDB shell commands on MongoDB 10Gen's driver

ε祈祈猫儿з 提交于 2020-02-03 05:39:05

问题


I want to simply execute pure MongoDB queries via MongoDb 10Gen's .net(c#) driver.

For example . I want to use below command on driver

db.people.update( { name:"Joe" }, { $inc: { n : 1 } } );

I am not sure how can i do this. I am not interested in how to do via high level api classes.


回答1:


The C# driver (or any other driver) is not intended to "directly" run mongo shell commands. That's what the shell is for. What you need to do is translate the mongo shell commands into the equivalent C# statements.

If you want to run mongo shell commands then run them in the mongo shell.




回答2:


You can construct queries i c# using the fluent Query interface. Those query can then be fired towards the databse using the Find method on a Mongo collection. E.g:

var myDatabase = MongoDatabase.Create(connectionString);
var myCollection = database.GetCollection<MyType>("myCollectionNameInDB");
var myCollection = 
var myQuery = Query.EQ("name", "joe");
var someDataFromDB =  myCollection.Find(myQuery).FirstOrDefault();

Query can also be used with updates. E.g.:

myCollection.Update(
                   myQuery,
                   Update.Replace(new MyType(){...}),
                   UpdateFlags.Upsert
              );

This just replaced the whole document. For finegrained control you can use the Update API combined with the FindAndModify method. E.g:

var myUpdate = Update.Inc("n", 1);
var result = myCollection.FindAndModify(
                   myQuery,
                   SortBy.Descending("name");
                   myUpdate,
                   true // return new document
             );

Check out http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial for more information.



来源:https://stackoverflow.com/questions/7947804/using-mongodb-shell-commands-on-mongodb-10gens-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!