Mongo更新数组元素(.NET驱动程序2.0) [英] Mongo update array element (.NET driver 2.0)

查看:77
本文介绍了Mongo更新数组元素(.NET驱动程序2.0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不寻找这样做的JavaScript方式.我正在寻找实现此目的的MongoDB C#2.0驱动程序方式(我知道这不可能;但是我希望有人知道解决方案).

Not looking for the javascript way of doing this. I am looking for the MongoDB C# 2.0 driver way of doing this (I know it might not be possible; but I hope somebody knows a solution).

我正在尝试更新mongodb主文档中数组中嵌入的项目的值.

I am trying to update the value of an item embedded in an array on the primary document in my mongodb.

我正在寻找一种强类型的方式来做到这一点.我正在使用 Mongodb c#2.0驱动程序

I am looking for a strongly typed way to do this. I am using the Mongodb c# 2.0 driver

我可以通过弹出元素,更新值然后重新插入来实现.这只是不对劲;因为我要覆盖这段时间内可能写的内容.

I can do it by popping the element, updating the value, then reinserting. This just doesn't feel right; since I am overwriting what might have been written in the meantime.

这是我到目前为止尝试过的,但是没有运气:

Here is what I have tried so far but with no luck:

private readonly IMongoCollection<TempAgenda> _collection;

void Main()
{
    var collectionName = "Agenda";
    var client = new MongoClient("mongodb://localhost:27017");
    var db = client.GetDatabase("Test");
    _collection = db.GetCollection<TempAgenda>(collectionName);
    UpdateItemTitle(1, 1, "hello");
}

public void UpdateItemTitle(string agendaId, string itemId, string title){
    var filter = Builders<TempAgenda>.Filter.Eq(x => x.AgendaId, agendaId);
    var update = Builders<TempAgenda>.Update.Set(x => x.Items.Single(p => p.Id.Equals(itemId)).Title, title);
    var result = _collection.UpdateOneAsync(filter, update).Result;
}

推荐答案

花点时间弄清楚这一点,因为在任何正式文档(或其他任何地方)中都没有提到它.但是,我在他们的问题跟踪器上确实找到了,它说明了如何在C#中使用位置运算符$ 2.0驱动程序.

Took me a while to figure this out as it doesn't appear to be mentioned in any of the official documentation (or anywhere else). I did however find this on their issue tracker, which explains how to use the positional operator $ with the C# 2.0 driver.

这应该做您想要的:

public void UpdateItemTitle(string agendaId, string itemId, string title){
    var filter = Builders<TempAgenda>.Filter.Where(x => x.AgendaId == agendaId && x.Items.Any(i => i.Id == itemId));
    var update = Builders<TempAgenda>.Update.Set(x => x.Items[-1].Title, title);
    var result = _collection.UpdateOneAsync(filter, update).Result;
}

请注意,您的Item.Single()子句已更改为Item.Any(),并已移至过滤器定义.

Notice that your Item.Single() clause has been changed to Item.Any() and moved to the filter definition.

[-1].ElementAt(-1)显然经过了特殊处理(实际上所有内容<0),并且将替换为位置运算符$.

[-1] or .ElementAt(-1) is apparently treated specially (actually everything < 0) and will be replaced with the positional operator $.

以上内容将翻译为该查询:

The above will be translated to this query:

db.Agenda.update({ AgendaId: 1, Items.Id: 1 }, { $set: { Items.$.Title: "hello" } })

这篇关于Mongo更新数组元素(.NET驱动程序2.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆