【问题标题】:How can I compare two bson.M data sets using Golang如何使用 Golang 比较两个 bson.M 数据集
【发布时间】:2020-05-16 12:11:42
【问题描述】:

我有以下代码,它从 MongoDB 数据库中的两个不同集合中检索两个数据集

    opts := options.Find()
    opts.SetProjection(bson.M{
        "productId": 1,
        "_id": 0,
    })

    cursor, err := currentProductsCollection.Find(ctx, bson.M{}, opts)
    var oldProducts []bson.M
    err = cursor.All(ctx, &oldProducts)

    cursor, err = newProductsCollection.Find(ctx, bson.M{}, opts)
    var newProducts []bson.M
    err = cursor.All(ctx, &newProducts)

我希望能够将oldProductsnewProducts 进行比较,以找出哪些新的productId 出现了,哪些旧的productId 消失了。

这两个变量都加载得很好,我可以很高兴地在调试器中检查它们,但我似乎找不到比较它们的方法。我曾希望能够依次遍历每个范围,对另一个进行查找并获得几片缺失值,但我找不到任何方法。

在过去的三个小时里,我一直带着这个在房子里转悠,所以如果有人有任何建议,我会非常欢迎他们。

我使用的是原版 go.mongodb.org/mongo-driver 驱动程序,而不是 mgo

【问题讨论】:

  • 我要感谢 Burak 和 Eklavya 的解决方案。我希望我可以将它们都标记为答案。

标签: mongodb go bson


【解决方案1】:

按产品 ID 为旧产品和新产品创建地图

oldProductsMap = make(map[interface{}]bson.M)
for _,oldp := range oldProducts {
   oldProductsMap[oldp["productId"]] = oldp
}

newProductsMap = make(map[interface{}]bson.M)
for _,newp :=range newProducts {
   newProductsMap[newp["productId"]] = newp
}

然后对于消失的产品检查旧产品在newProductsMap。如果没有,那么产品就消失了

var disProducts []bson.M
for _,oldp := range oldProducts {
   if _, ok := newProductsMap[oldp["productId"]]; !ok {
       disProducts = append(disProducts, oldp) 
   }
}

对于新出现的产品,检查新产品在oldProductsMap。如果不是,则新出现的产品。

var appProducts []bson.M
for _,newp := range newProducts {
   if _, ok := oldProductsMap[newp["productId"]]; !ok {
       appProducts = append(appProducts, oldp)
   }
}

注意你也可以在为新产品创建地图时做这部分

【讨论】:

  • 这看起来可能是我正在寻找的东西。我尝试制作地图,但我尝试的 map[string]interface{} 不起作用。非常感谢您的回复。
  • 嗯,不能使用 oldp["productId"] (type interface {}) 作为地图索引中的 int 类型:需要类型断言和 newp 的相同消息。
  • 您可以使用map[interface{}]bson.M。我更新了我的答案
【解决方案2】:

如果您确定所有条目都有productId 字段:

func exists(in []bson.M,id interface{}) bool {
   for _,p:=range in {
     if id==p["productId"] {
        return true
     }
   }
  return false
}

然后使用它来扫描两个列表:

for _,oldp:=range oldProducts {
   if !exists(newProducts,oldp["productId"]) {
     // Removed
   }
}

for _,newp:=range newProducts {
   if !exists(oldProducts,newp["productId"]) {
     // Added
   }
}

【讨论】:

  • 是的,肯定所有条目都有productId。我会在早上尝试您的解决方案,非常感谢您的回复。
  • 嗯,我得到:“无效操作:id==in["productId"](操作符 == 未在 bson.M 上定义)”
  • 应该是 p["productId"]。我确定了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-30
  • 2015-07-10
  • 2014-08-30
  • 1970-01-01
  • 2020-09-30
  • 2015-06-12
相关资源
最近更新 更多