如何使用 Golang 比较两个 bson.M 数据集

How can I compare two bson.M data sets using Golang

我有以下代码,它从 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 消失了。

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

在过去的三个小时里,我一直带着它四处走动,所以如果有人有任何建议,我将非常欢迎他们。

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

如果您确定所有条目都有 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
   }
}

按产品 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)
   }
}

注意 : 您也可以在为新产品创建地图时执行此部分