【问题标题】:Update in a document based on $or filter基于 $or 过滤器更新文档
【发布时间】:2015-12-04 14:39:44
【问题描述】:

我有喜欢的收藏

{
"_id": ObjectId("565ff61d454231a81753866a"),
"tripMembers" : [ 
        {
            "username" : "akshay.kumar@gmail.com",
            "contact" : null,
            "userId" : "1234999",
            "accept" : 2,
            "_id" : ObjectId("565ff61d454231a817538664")
        }, 
        {
            "username" : "akshay@gmail.co",
            "contact" : null,
            "userId" : "",
            "accept" : 0,
            "_id" : ObjectId("565ff61d454231a817538665")
        }]
}

我想更新数组中对象的键。我正在使用以下查询,但它不起作用

db.trips.update({
    $or :[
        {"tripMembers.username" : "akshay.kumar@gmail.com"},
       {"tripMembers.contact": "1234999" }]
    },
    {"_id" :ObjectId("565ff61d454231a81753866a")},
    {$set : {"tripMembers.accept" :1}
})

它给了我错误位置运算符没有从查询中找到所需的匹配项。未扩展更新:tripMembers.$.accept

如果我尝试相同的查询,$or 运算符中只有一个条件,它的工作正常

db.trips.update({
    $or :[
        {"tripMembers.username" : "akshay.kumar@gmail.com"}  
    },
    {"_id" :ObjectId("565ff61d454231a81753866a")},
    {$set : {"tripMembers.accept" :1}
})

不知道,我哪里错了。任何帮助。

【问题讨论】:

  • 你想用{"_id" :ObjectId("565ff61d454231a81753866a")}做什么?看起来您的更新有语法错误,它从那里开始。你的 `$set` 似乎是第三个参数,它应该是第二个。

标签: node.js mongodb


【解决方案1】:

不应该是:

b.trips.update({
    $and:
        [{$or :[
            {"tripMembers.username" : "akshay.kumar@gmail.com"}  
        ]},
        {"_id" :ObjectId("565ff61d454231a81753866a")}]
    },
    {$set : {"tripMembers.accept" :1}})

?

【讨论】:

  • 不幸的是我不能。请修改您的帖子并修复括号
【解决方案2】:

右 ] 大括号的位置不正确。

db.trips.update({
    $or :[
        {"tripMembers.username" : "akshay.kumar@gmail.com"},
       {"tripMembers.contact": "1234999" }] <<--- no closing brace here
    },
    {"_id" :ObjectId("565ff61d454231a81753866a")}, << -- your update clause as David points out. This will wipe out all subdocs and leave only _id. urp!
    {$set : {"tripMembers.accept" :1} << -- not executed. irrelevant
})

试试

db.trips.update({
    $or :[
        {"tripMembers.username" : "akshay.kumar@gmail.com"},
       {"tripMembers.contact": "1234999" },
       {"_id" :ObjectId("565ff61d454231a81753866a")}],
    {$set : {"tripMembers.accept" :1}
})

进一步根据您的数据。一个小的oversite。

       "contact" : null,
        "userId" : "1234999",

很可能是 $or ... {"tripMembers.userId": "1234999" },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多