search

Home  >  Q&A  >  body text

mongodb中$or和upsert兼容问题

今天碰到一个问题,当我在update数据的时候想使用upsert功能,发现插入的数据并没有过滤条件中$or的部分,如下:

db.msg.update(
    {
        “type”: “u”,
        “$or”: [
            {“from”: 1, “to”: 2},
            {“from”: 2, “to”: 1}
        ]
    },
    {
        “$push”: {
            “message”: {
                “data”: “holla”,
                “status”: false,
                “time”: new Date()
            }
        }
    },
    true,
    true
);

本来希望的是:如果发现msg集合中如果没有对应文档,则插入,例如上面的这条更新(假设当前集合中不存在from:1,to:2的这个文档),执行完后msg集合中应当出现下面这个文档:

{
    "from": 1,
    "to": 2,
    "type": "u",
    "message": [
        {
            “data”: “holla”,
            “status”: false,
            “time”: ISODate("2014-02-12T01:50:40.866Z")
        }
    ]
}

可实际情况是插入的数据中并不会包含$or部分的条件,请问有没有解决方案?

PHPzPHPz2767 days ago594

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-22 09:00:57

    $upsert currently (2.4) does not support $and and $or, but it is said that 2.6 supports it. See official issues:

    • $or paired with upsert does not create documents for each or clause
    • Insert from update (w/upsert:true) ignores $and equality fields

    reply
    0
  • 高洛峰

    高洛峰2017-04-22 09:00:57

    upsert This method is inherently unreliable, and it is clearly written in the manual

    Warning: To avoid inserting the same document more than once, only use upsert: true if the query field is uniquely indexed.

    So you ignored me?

    reply
    0
  • Cancelreply