gpt4 book ai didi

MongoDB,添加新的 { 字段 : value } in existing embedded document with multiple level dot notation?

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

我要做的是为博客文章添加一个新的 {field:value}。例如,如果我想开始跟踪 website.blog_posts.url: 'http://www.example.com/01.html' 上的展示次数,我该如何为该博客文章添加展示次数属性?

我当前的文档结构:

{ 
email_address: 'webmaster@example.com',
password: 'random_password',
first_name: 'John',
last_name: 'Doe',
user_type: 'WEBMASTER',
newsletter: 'NO',
websites: [{
main_title: 'My Blog Website',
main_url: 'http://www.example.com',
blog_posts: [{
url: 'http://www.example.com/01.html',
title:'My first blog post',
description: 'My first description.'
}, {
url: 'http://www.example.com/02.html',
title: 'My second blog post',
description: 'My second description.'
}, {
url: 'http://www.example.com/03.html',
title: 'My third blog post',
description: 'My third description.'
}, {
url: 'http://www.example.com/04.html',
title: 'My fourth blog post',
description: 'My fourth description.'
}]
}]
}

这是我认为使用 update 并将 upsert 设置为 TRUE 的方法。

db.my_collection.update( {'websites.blog_posts.url': 'http://www.example.com/01.html' }, {'$set': {'websites.blog_posts.impressions': 549}}, true )

我收到的错误是:*无法使用字符串字段名称 [blog_posts]*

附加到数组

也许“$set”对此不正确,或者我不能用点符号引用那么深?我昨天才开始使用 MongoDB,任何帮助都会很棒。

谢谢!

最佳答案

鉴于您的架构,您尝试做的事情是不可能的。点表示法可以是多级的,但如果有多个级别是一个数组,则不能再使用位置运算符“$”来处理它。

例如你需要这样做:

db.my_collection.update( 
{'websites.blog_posts.url': 'http://www.example.com/01.html' },
{'$set': {'websites.$.blog_posts.$.impressions': 549}},
true );

但是在更新中有两个位置操作符是不可能的,因为 MongoDB 只能确定一个元素在第一个数组中的位置。

您唯一的选择是重新设计您的架构,以拥有一个专用的用户网站集合(在这种情况下,出于其他原因,这也更好)。

关于MongoDB,添加新的 { 字段 : value } in existing embedded document with multiple level dot notation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7916476/

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