如何通过C#将新的包含数据的列插入MongoDB中的集合?

问题描述 投票:0回答:1

我有两个字段应该比较,并据此采取措施:

if(x == y) then x = [new Field called Z]
else [new Field called Z] = Math.Random

如何使用MongoDB在C#中做到这一点?

.net mongodb mongodb-.net-driver
1个回答
1
投票

假设您具有以下定义为的实体类Item

public class Item
{
    [BsonId]
    public String Id {get; set;}

    public int a {get; set;}

    public int x {get; set;}

    public int y {get; set;}
}

使用MongoDB C# Driver,您可以首先使用SetFields类的[SetFields方法检索想要的两个字段:

MongoCursor
从这里您可以遍历光标,进行比较。如果要在要插入新字段MongoCursor的地方执行更新操作,则此方法应该有效

var server = MongoServer.Create(connectionString); var db = server.GetDatabase("dbName"); MongoCollection collection = db.GetCollection<Item>("items"); MongoCursor<Item> cursor = collection.FindAs<Item>(Query.EQ("a", 33)); //if you want to match specific docs else Query.Null cursor.SetFields(Fields.Include("x", "y")); var items = cursor.ToList(); foreach (var item in items) { // compare item.x and item.y and act accordingly }

© www.soinside.com 2019 - 2024. All rights reserved.