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

虾米哥 阅读:44 2025-06-02 22:19:02 评论:0

我有以下代码,该代码从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

请您参考如下方法:

通过产品ID为旧产品和新产品创建 map

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 时执行此部分


标签:mongodb
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号