MongoDB:允许每个用户拥有自己的共享文档版本,保留ID

MongoDB: Allow each user to have their own version of a shared document, keeping the ID

我有一个 MongoDB 产品集合,所有用户都可以从网站上查看这些产品,但我希望允许每个用户编辑这些产品的属性(名称、价格等),同时保留原始信息编号.

基本上每个用户都会有自己的产品版本,同时仍然指向其他人使用的相同共享产品。如果可能的话,用户将获取 Products 集合,用编辑过的产品替换“默认”共享产品(用户很可能不会编辑每个产品,所以我尽量避免为每个用户复制整个集合)。

这样的事情可行吗?我将如何构建它?

示例:

ORIGINAL PRODUCT
id: abc
name: "Car"
price: 50000

USER 1
id: abc
name: "Some car"
price: 64000

USER 2
id: abc
name: "Red car"
price: 48000

/* These all refer to the same product (same id) */

简单的将用户的修改根据用户的id存储在嵌入文档中

{
  id: "abc",
  name: "Car",
  price: 50000,
  "modifications" : [
    {
      "user_id" : 1, 
      "name" : "Some car", 
      "price" : 64000.0
    }, 
    {
      "user_id" : 2, 
      "name" : "Red car", 
      "price" : 48000.0
    }
  ]
}

查询时,使用聚合管道将用户特定值合并为全局值:

var user_id = 1234
db.cars.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: {
          $let: {
            vars: {
              userModifications: {
                $first: {
                  $filter: {
                    input: "$modifications",
                    as: "modification",
                    cond: { $eq: ["$$modification.user_id", user_id] }
                  }
                }
              }
            },
            in: ["$$ROOT", "$$userModifications"]
          }

        }
      }
    },
  },
  {
    $project: { modifications: 0 }
  }
])