MongoDB,在现有嵌入文档中添加新的{field:value}并使用多级点表示法?
我想做的是为一篇博客文章添加一个新的{field:value}。例如,如果我想开始跟踪网站上的印象。blog_posts.url:'http://www.example.com/01.html'如何为该博客文章添加“印象”属性 我当前的文档结构:MongoDB,在现有嵌入文档中添加新的{field:value}并使用多级点表示法?,mongodb,Mongodb,我想做的是为一篇博客文章添加一个新的{field:value}。例如,如果我想开始跟踪网站上的印象。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: 'WEB
{
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成为现实的方法
更新({'websites.blog_posts.url':'http://www.example.com/01.html“},{$set:{'websites.blog_posts.impressions':549},true)
我收到的错误是:
*无法使用字符串字段名[blog\u 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只能确定元素在第一个数组中的位置
您唯一的选择是重新设计您的模式,以拥有一个专用的用户网站集合(在本例中,这也是出于其他原因而更好)。您是对的,我的问题是我的模式和用于存储嵌入文档的不正确方括号。相反,我使用括号表示数组。我现在已经成功地添加了新的字段4级深使用点符号和适当的模式。