Update MongoDB Document in VB.NET with the C# Driv

2019-06-14 14:39发布

I am having problems updating a document in MongoDB using VB.NET & the C# Driver.

I have code returning the document I wish to update but I'm not sure of the syntax to continue

Imports MongoDB.Bson
Imports MongoDB.Driver
Imports MongoDB.Driver.Builders

Dim mongo As MongoServer = MongoServer.Create()
mongo.Connect()
Dim db = mongo.GetDatabase("database")
Dim stock = db.GetCollection(Of BsonDocument)("stock")

Dim getDocument = New QueryDocument("productName", "test")

3条回答
欢心
2楼-- · 2019-06-14 15:23

Use the coll.update method. e.g. to set the value of a field

Dim client = New MongoClient()
Dim db = client.GetServer().GetDatabase("test")
Dim coll = db.GetCollection("vbtest")
Dim productQuery = Query.EQ("productName", "test")
Dim updateStmt = Update.Set("cost", 3000)
coll.Update(productQuery, updateStmt)

More information on the methods can be found at http://api.mongodb.org/csharp/1.8.1/. Also I would recommend going through the tutorials at http://docs.mongodb.org/ecosystem/drivers/csharp/. The examples are in C# though

查看更多
姐就是有狂的资本
4楼-- · 2019-06-14 15:35

My solution, you can use same this block code:

Imports MongoDB.Bson
Imports MongoDB.Driver

Connect to Mongodb:

public client As MongoClient = New MongoClient("mongodb://user:password@IP:27017/MyDatabase")
public mydb As IMongoDatabase = client.GetDatabase("MyDatabase")
public userCollection As IMongoCollection(Of BsonDocument) = mydb.GetCollection(Of BsonDocument)("users")

Update:

Dim filterById = Builders(Of BsonDocument).Filter.Eq(Of String)("_id", userId)
userCollection.UpdateOne(filterById, New BsonDocument("$set", New BsonDocument("emailField", newEmail)))

Goodluck!

查看更多
登录 后发表回答