如何通过 C# 将包含数据的新列插入 MongoDB 中的集合?
How can I insert a new column with data to a collection in MongoDB, through C#?
我有两个字段需要比较并相应地采取行动:
if(x == y) then x = [new Field called Z]
else [new Field called Z] = Math.Random
如何使用 MongoDB 在 C# 中执行此操作?
假设您将以下实体 class 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, you could start by retrieving the two fields you want using SetFields
method of MongoCursor
class:
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
}
从这里您可以遍历游标,进行比较。如果您想在要插入新字段的地方执行更新操作 z
那么这应该有效
collection.Update(Query.Null, Update.Set("z", Math.Random), UpdateFlags.Multi)
我有两个字段需要比较并相应地采取行动:
if(x == y) then x = [new Field called Z]
else [new Field called Z] = Math.Random
如何使用 MongoDB 在 C# 中执行此操作?
假设您将以下实体 class 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, you could start by retrieving the two fields you want using SetFields
method of MongoCursor
class:
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
}
从这里您可以遍历游标,进行比较。如果您想在要插入新字段的地方执行更新操作 z
那么这应该有效
collection.Update(Query.Null, Update.Set("z", Math.Random), UpdateFlags.Multi)