在 Cloud Firestore 中更新特定文档字段与整个文档的成本效率

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

我正在使用 Firebase 作为 BaaS 开发 UIKit 应用程序。

请考虑以下场景:用户想要更改他们的用户名,并且我在 Firestore 中有一个用于其个人资料的文档,例如包含用户用户名和电子邮件字段的文档。

是否有任何官方文档证实,从客户端重新保存整个文档,将其与现有文档(如果有)合并,比专门更新用户名字段更昂贵?

请注意,虽然远低于实时数据库,但您仍然需要为从 Firestore 数据库读取和写入的字节数付费。

请不要问我为什么想知道这个、这如何运作或任何与问题无关的问题。

这是一个快速示例,以防它使我的问题更清楚:

class DatabaseController {
    let db: Firestore
    let authController: AuthControllerProtocol
        
    init(
        db: Firestore = .firestore(),
        authController: AuthControllerProtocol
    ) {
        self.db = db
        self.authController = authController
    }
    
    // first function: save the whole document each time, merging it with the existing one, if any
    func save(_ profile: Profile) async {
        guard let currentUserUid = authController.auth.currentUser?.uid else {
            print(">> \(Self.self).\(#function): could not find currentUserUid")
            return
        }
        
        do {
            let encodedProfile = try Firestore.Encoder().encode(profile)
            do {
                try await db.collection("users").document(currentUserUid).setData(encodedProfile, merge: true)
            } catch {
                print(">> \(Self.self).\(#function): could not update profile: \(error.localizedDescription)")
                return
            }
        } catch {
            print(">> \(Self.self).\(#function): could not encode profile: \(error.localizedDescription)")
        }
    }
    
    // second function: only update the specific field that you know should be updated
    func save(_ username: String) async {
        guard let currentUserUid = authController.auth.currentUser?.uid else {
            print(">> \(Self.self).\(#function): could not find currentUserUid")
            return
        }
        
        do {
            try await db.collection("collection").document("\(currentUserUid)").setData(["key": username], merge: true)
        } catch {
            print(">> \(Self.self).\(#function): could not update username: \(error.localizedDescription)")
            return
        }
    }
}
google-cloud-firestore
1个回答
0
投票

无论您编写多少个字段,编写文档的价格都是相同的。由于您无需为传入带宽付费,因此这也没有什么区别。如果这些方法之间存储的文档最终相同,则存储成本也将相同。

有关 Firestore 定价的完整详细信息,请参阅:https://cloud.google.com/firestore/pricing

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