首页 > mongodb中$or和upsert兼容问题

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部分的条件,请问有没有解决方案?


$upsert当前(2.4)是不支持$and和$or的,据说2.6支持。见官方issues:


upsert 本来就是不靠谱的方法,manual 上也写的很清楚

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

于是被你无视了?

【热门文章】
【热门文章】