gpt4 book ai didi

mongodb - 在 mongodb 中更新子文档?

转载 作者:IT老高 更新时间:2023-10-28 13:04:03 26 4
gpt4 key购买 nike

如何定位 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com