我有两个字段应该比较,并据此采取措施:
if(x == y) then x = [new Field called Z]
else [new Field called Z] = Math.Random
如何使用MongoDB在C#中做到这一点?
假设您具有以下定义为的实体类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 }