实际上,我正在尝试替换我的集合“游戏”中类型为Game的对象的集合。
我想用全新的对象替换这些对象。我对MongoDB进行了一些研究,我发现'UpdateMany‘会用新的值替换字段,但这并不是我想要的。我希望替换整个对象。
作为参考,这是我的Game类:
public class Game
{
  public Guid Id { get; set; }
  public string Title { get; set; }
  public string Developer { get; set; }
  public int ProjectId { get; set; }
  public Game()
  {
   this.Id = Guid.NewGuid();
 }
}这是我用来尝试批量替换的方法。我传入了一个ProjectId,所以对于所有带参数ProjectId =的游戏对象,用一个新的游戏对象替换这个对象。
 public static void ReplaceGame(int ProjectId, IMongoDatabase Database)
 {
   IMongoCollection<Game> gameCollection = Database.GetCollection<Game>("Game");
   List<Game> gameCollectionBeforeReplacement = gameCollection.Find(g => true).ToList();
   if (gameCollectionBeforeReplacement.Count == 0)
   {
     Console.WriteLine("No Games in Collection...");
     return;
    }
    var filter = Builders<Game>.Filter.Eq(g => g.ProjectId, ProjectId);
    foreach (Game game in gameCollection.AsQueryable())
        gameCollection.ReplaceOneASync(filter, new Game() { Title = "REPLACEMENT TITLE" });
    }这不仅需要过多的时间。我怀疑这是因为调用了.AsQueryable(),但它也不能工作。我想知道怎样才能用新的游戏对象替换所有被我的过滤器拾取的实例。
发布于 2018-06-18 23:14:18
考虑以下代码:
public virtual ReplaceOneResult ReplaceOne(TDocument replacement, int projId)
{
    var filter = Builders<TDocument>.Filter.Eq(x => x.ProjectId, projId);
    var result = Collection.ReplaceOne(filter, replacement, new UpdateOptions() { IsUpsert = false }, _cancellationToken);
    return result;
}您会发现ReplaceOneResult有一个属性来告诉您匹配的计数。这使您可以继续执行ReplaceOne调用,直到匹配的计数等于0。当发生这种情况时,您知道集合中具有相应项目id的所有文档都已被替换。
示例:
var result = ReplaceOne(new Game() { Title = "REPLACEMENT TITLE" }, 12);
while (result.MatchedCount > 0)
    result = ReplaceOne(new Game() { Title = "REPLACEMENT TITLE" }, 12);这使得您在开始替换之前不需要调用数据库。
但是,如果您希望为每个现有游戏插入相同的值,我建议您执行UpdateMany操作。在那里,您可以使用$set指定所有必需的值。上面的代码性能很差,每次调用replace时都要访问数据库。
https://stackoverflow.com/questions/50874994
复制相似问题