基于$或过滤器更新文档

时间:2015-12-03 19:00:21

标签: node.js mongodb

我有像

这样的集合
{
"_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。$。接受

如果我在$or运算符中仅尝试相同的查询,则其工作正常

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

不知道,我哪里错了。任何帮助都很明显。

2 个答案:

答案 0 :(得分:0)

不应该是:

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

答案 1 :(得分:0)

关闭]括号只是处于错误的位置。

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}
})

进一步根据您的数据。一个小小的过分。

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

很可能是$或...... {&#34; tripMembers。 userId &#34;:&#34; 1234999&#34; },