仅当文档字段尚不存在时,如何创建它?

问题描述 投票:0回答:1

如果文档尚不存在,我想将其添加到文档中,但如果存在则不更新它。直接使用 mongodb 我会使用:

db.foo.update({'_created_by': {$exists : false}}, {$set: {'_created_by': 'x'}})

但是,我使用 Rust,如果该字段已存在,我当前的代码会覆盖该字段:

update_doc.insert(format!("{}._created_by"), bson!("x"));

如何在 Rust 中实现

{$exists : false}
部分?

mongodb rust bson
1个回答
0
投票

在 Rust 中,您可以通过使用

$exists: false
运算符和
$not
查询来实现与 MongoDB 中的
$exists
相同的行为。以下是如何修改代码来实现此目的的示例:

use mongodb::{bson::{doc, Bson}, options::UpdateOptions, Collection};

fn add_field_if_not_exists(collection: &Collection) -> Result<(), mongodb::error::Error> {
    let filter = doc! {
        "_created_by": doc! {
            "$not": doc! {
                "$exists": true
            }
        }
    };

    let update = doc! {
        "$set": {
            "_created_by": "x"
        }
    };

    let options = UpdateOptions::builder()
        .upsert(false) // Set to false to not insert the field if it doesn't exist
        .build();

    collection.update_one(filter, update, options)?;

    Ok(())
}

在此代码中,我们正在构建一个

filter
文档,该文档使用
$not
运算符和
$exists: true
来查找
_created_by
字段不存在的文档。然后,我们构建一个
update
文档,如果过滤器匹配,则将
_created_by
字段设置为“x”。

最后,我们使用

update_one()
方法来执行更新操作。
upsert
选项设置为
false
以确保该字段不存在时不会插入。

我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.