【问题标题】:Update multi nested array in Mongodb更新 Mongodb 中的多嵌套数组
【发布时间】:2013-04-14 19:18:34
【问题描述】:

我在 Mongodb 中有一个如下所示的文档架构:

{
    _id: 1
    tags: [{
        tag: 'foo'
        links: [{
            link: 'http:www.google.com'
            date: '123'
        }] 
    }]
}

我正在尝试将链接推送到文档独有的“链接”数组中。

我的第一个查询...

db.userlinks.update (
    {_id: 1, tags: {$nin: [{tag:'foo'}]}}, 
    {$push: {'tags': {tag:'foo'}}}, 
    {upsert: true}
)

给我这个(如果它不存在则创建标签)

{ "_id" : 1, "tags" : [ { "tag" : "foo" } ] }

然后我用这个查询来跟进......

db.userlinks.update (
    {_id: 1, tags: {tag: 'foo', links: {$nin: [{link: 'http://www.google.com'}]}}}, 
    {$push: {tags: {tag: 'foo', links: {link: 'http://www.google.com', date: '123'}}}}, 
    {upsert: true}
)

但我收到此错误:“无法将 $push/$pushAll 修饰符应用于非数组”

我很确定问题出在我的第二个查询的“更新”组件中,但我不确定如何解决它。任何帮助将不胜感激。

编辑

我的第一个查询现在是...(感谢 Joe)

db.userlinks.update (
    {_id: 1, tags: {$nin: [{tag:'foo'}]}}, 
    {$push: {'tags': {tag:'foo', links:[]}}}, 
    {upsert: true}
)

我的第二个查询现在是...

db.userlinks.update (
    {_id: 1, 'tags.tag': 'foo'}, 
    {$push: {'tags.$.links': {link: 'http://www.google.com', date: '123'} } }
)

这成功地将链接推送到“链接”数组中,但它也允许重复。我不能允许重复的链接。 $addToSet 可以工作,但是如果日期发生变化,它仍然会插入一个重复的链接。

有没有办法在我的第二个查询的“查询”部分检查链接是否存在,或者只在某些字段匹配时才 addToSet?

【问题讨论】:

  • 你不能。考虑改变你的架构?
  • 我并不是特别想更改我的架构,因为这是完全按照它的输出方式建模的,这意味着一旦我将它从数据库中取出,我就不必进行任何数据整理.我认为这应该是实际上使用 Mongodb 的主要原因?直接将对象建模进出数据库的能力。

标签: mongodb


【解决方案1】:

我终于明白了...尽管如果有人能找到更好的方法,请将其添加为答案。

// create the userlinks collection if it doesn't exist
// also add a tag 'foo' into it, but only if the tag doesn't exist
db.userlinks.update (
    {_id: '1', 'tags.tag': {$nin: ['foo']}}, 
    {$push: {'tags': {tag:'foo', links:[]}}},
    {upsert: true}
)

// add a link into the 'foo' tag, but only if the link doesn't exist
db.userlinks.update(
    {_id: '1', 'tags.tag': 'foo', 'tags.links.link': {$nin: ['http://foobar.com']}},
    {$push: {'tags.$.links': {link: 'http://foobar.com', date: '15'} } }
)

【讨论】:

  • @Harley : 如果我们知道 _id 、 'tags.tags' 和 'tags.links.link'...db.doc.update({_id : , 'tags.tags : , 'tags.links.link': },{$inc : {'tags.links.$.date' : 20}}) 不起作用,因为我们有两个数组..请帮助
  • 抱歉,Praveen,自从我发表这篇文章后,我就再也没有与 Mongo 合作过,恐怕我基本上已经忘记了查询语言的复杂性。也许打开一个新问题?
【解决方案2】:

也许将您的第一个查询更改为:

db.userlinks.update (
    {_id: 1, tags: {$nin: [{tag:'foo'}]}}, 
    {$push: {'tags': {tag:'foo', links:[]}}}, 
    {upsert: true}
)

$push 操作应该只影响链接,而不是标签。

{$push: {'tags.links': {link: 'http://www.google.com', date: '123'} } },

【讨论】:

  • 这将“链接”启动到一个空数组,这很好,可能是我需要的,但是我的第二个查询仍然引发同样的错误。
  • 不幸的是,使用它作为第二个查询我仍然有同样的错误:db.userlinks.update ( {_id: 1, tags: {tag: 'foo', links: {$nin: [ {link: 'google.com'}]}}}, {$push: {'tags.links': {link: 'google.com', date: '123'} } }, {upsert: true})
猜你喜欢
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多