mongodb - 在 mongodb 中更新子文档?

标签 mongodb

如何定位 authors 数组中的子文档,如下所示,以便更新它?

collection.update({'_id': "4f44af6a024342300e000001"}, {$set: { 'authors.?' }} )

文件:

{
    _id:     "4f44af6a024342300e000001",
    title:   "A book", 
    created: "2012-02-22T14:12:51.305Z"
    authors: [{"_id":"4f44af6a024342300e000002"}] 
}

最佳答案

通过像这样指定嵌入文档的实际位置:

// update _id field of first author    
collection.update({'_id': "4f44af6a024342300e000001"}, 
                  {$set: { 'authors.0._id': "1" }} )

或通过 positional operator :

// update _id field of first matched by _id author    
collection.update({'_id': "4f44af6a024342300e000001",
                    //you should specify query for embedded document
                    'authors._id' : "4f44af6a024342300e000002" }, 
     // you can update only one nested document matched by query                   
                    {$set: { 'authors.$._id': "1" }} )

关于mongodb - 在 mongodb 中更新子文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9401668/

相关文章:

node.js - 当 native JS .forEach() 阻塞时,MongoDb 游标方法 .forEach() 是非阻塞的

ruby-on-rails - MongoDB Rails3.2 数据库命令 'create' 失败

node.js - Node js,%1 不是有效的 Win32 应用程序,js-bson : failed to load c++ bson extension, windows

node.js - POST 400 错误请求、React、Node/Express、MongoDB

node.js - 从终端启动 Mongod 和 Mongo

mongodb - 如何使用GoLang mongodb驱动程序在mongodb中搜索文档,其中文档中的值为字符串,并且过滤器具有字符串 slice ?

c# - MongoDB C# 驱动程序 - 如何查询子文档数组的属性

mysql - 相当于 MYSQL 中 COUNT (`column` ) 的 mongodb 是什么?

javascript - mongodb - 聚合游标计数

mysql - Spring启动MongoDB配置