相关疑难解决方法(0)

MongoDB - 更新文档数组中的对象(嵌套更新)

假设我们有以下集合,我几乎没有问题:

{
    "_id" : ObjectId("4faaba123412d654fe83hg876"),
    "user_id" : 123456,
    "total" : 100,
    "items" : [
            {
                    "item_name" : "my_item_one",
                    "price" : 20
            },
            {
                    "item_name" : "my_item_two",
                    "price" : 50
            },
            {
                    "item_name" : "my_item_three",
                    "price" : 30
            }
    ]
}
Run Code Online (Sandbox Code Playgroud)

1 -我要加大对"ITEM_NAME"的价格:"my_item_two" ,如果不存在的话,它应该被追加到"项"阵列.

2 - 如何同时更新两个字段.例如,增加"my_item_three"的价格,同时增加"total"(具有相同的值).

我更喜欢在MongoDB端执行此操作,否则我必须在客户端(Python)中加载文档并构造更新的文档并将其替换为MongoDB中的现有文档.

更新 这是我尝试过的,并且如果对象存在则工作正常:

db.test_invoice.update({user_id : 123456 , "items.item_name":"my_item_one"} , {$inc: {"items.$.price": 10}})
Run Code Online (Sandbox Code Playgroud)

但如果密钥不存在则无效.它也只更新嵌套对象.此命令无法更新"total"字段.

mongodb

193
推荐指数
3
解决办法
18万
查看次数

更新mongodb文档中的特定字段

我使用C#驱动程序在小项目中使用MongoDb,现在我坚持更新文档.试图弄清楚如何更新字段AVG(int)

这是我的代码:

IMongoCollection<Student> studentCollection = db.GetCollection<Student>("studentV1");

Student updatedStudent = new Student() { AVG = 100, FirstName = "Shmulik" });

studentCollection.UpdateOne(
        o=>o.FirstName == student.FirstName,
            **<What should I write here?>**);
Run Code Online (Sandbox Code Playgroud)

有简单而干净的方法来更新特定字段,如方法ReplaceOne(updatedStudent)

c# mongodb mongodb-query

13
推荐指数
2
解决办法
2万
查看次数

标签 统计

mongodb ×2

c# ×1

mongodb-query ×1