【问题标题】:MongoDB query: If two docs are referencing each other, eliminate one doc (Keep one combination only)MongoDB 查询:如果两个文档相互引用,则删除一个文档(仅保留一个组合)
【发布时间】:2022-01-10 14:55:12
【问题描述】:

我有这样的文档:

{
_id:61af43169dae3a9c3e133a90
name:"user1",
status: "RECOMMENDED",
recommendedId:61b708b8041895f4c68a3b3d
}

{
_id:61b708b8041895f4c68a3b3d
name:"user2",
status: "RECOMMENDED"
recommendedId:61af43169dae3a9c3e133a90
}

两个用户都是相互推荐的,因此,我不希望两个文档都填充了推荐的 ID。我只想要一个填充了推荐 ID 的文档(只保留一个组合)

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    我会在首先设置recommendedId 的值时尝试防止这种情况发生。

    因此,在尝试设置值之前,您可以执行以下操作:

    const idToRecommend = Types.ObjectId()
    
    const recommenders = await Foo.find({
       _id: idToRecommend,
       recommendedId: user._id
    })
    
    if (recommenders.length > 0) {
        // We don't want to make the change, we already have a relationship recorded.
    }
    

    清理已经被这些重复关系污染的数据库是一个不同的问题,但我会将此作为一次性任务而不是过程问题。

    【讨论】:

      猜你喜欢
      • 2020-06-27
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多