mongodb中$or和upsert兼容问题
PHPz
PHPz 2017-04-22 08:58:57
[MongoDB讨论组]

今天碰到一个问题,当我在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部分的条件,请问有没有解决方案?

PHPz
PHPz

学习是最好的投资!

全部回复(2)
PHP中文网

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

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

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

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

于是被你无视了?

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号