GVKun编程网logo

通过在golang中检查MongoDB中的多个属性值来检索项目列表(mongodb如何分析查询操作使用了哪些索引)

22

在本文中,我们将给您介绍关于通过在golang中检查MongoDB中的多个属性值来检索项目列表的详细内容,并且为您解答mongodb如何分析查询操作使用了哪些索引的相关问题,此外,我们还将为您提供关于

在本文中,我们将给您介绍关于通过在golang中检查MongoDB中的多个属性值来检索项目列表的详细内容,并且为您解答mongodb如何分析查询操作使用了哪些索引的相关问题,此外,我们还将为您提供关于Golang 和 MongoDB - 我尝试使用 golang 将切换布尔值更新为 mongodb,但得到了对象、golang中如何实现MongoDB数据的修改、golang中的Mongodb聚合、Golang无法在MongoDB中创建文档的知识。

本文目录一览:

通过在golang中检查MongoDB中的多个属性值来检索项目列表(mongodb如何分析查询操作使用了哪些索引)

通过在golang中检查MongoDB中的多个属性值来检索项目列表(mongodb如何分析查询操作使用了哪些索引)

这个问题基于MongoDB,如何通过选择多个条件来检索所选项目。就像Mysql中的IN条件一样

选择*从场所列表WHERE场所ID输入(场所1,场所2)

我已经附加了我使用过的json数据结构。 [参考:MONGODB的JSON STRUCTUE]

例如,它具有一个场所列表,然后在场所列表内,它具有多个属性场所ID,用户代理名称的总和以及总计数作为值。用户代理表示用户Os,浏览器和设备信息。在这种情况下,我使用os
distribution。在这种情况下,我是linux,ubuntu是指特定的场所ID。

就是这样

"sum" : [    {        "name" : "linux",        "value" : 12    },    {        "name" : "ubuntu",        "value" : 4    }],

最后,我想通过在MongoDB的一个find查询中选择“ eventidid”列表来获取所有linux用户数。

例如,我想通过条件ID为 VID1212 VID4343的 条件来选择所有Linux用户数 __

参考:MONGODB的JSON结构

{    "_id" : ObjectId("57f940c4932a00aba387b0b0"),    "tenantID" : 1,    "date" : "2016-10-09 00:23:56",    "venueList" : [        {            "id" : “VID1212”,            "sum" : [                {                      "name" : "linux",                      "value" : 12                },                {                    "name" : "ubuntu",                    "value" : 4                }            ],            “ssidList” : [    // this is list of ssid’s in venue                {                    "id" : “SSID1212”,                    "sum" : [                        {                            "name" : "linux",                            "value" : 8                        },                        {                            "name" : "ubuntu",                            "value" : 6                        }                    ],                    “macList” : [  // this is mac list inside particular ssid  ex: this is mac list inside the SSID1212                        {                            "id" : “12:12:12:12:12:12”,                            "sum" : [                                {                                    "name" : "linux",                                    "value" : 12                                },                                {                                    "name" : "ubuntu",                                    "value" : 1                                }                            ]                        }                    ]                }            ]        },        {            "id" : “VID4343”,            "sum" : [                {                     "name" : "linux",                     "value" : 2                }            ],            "ssidList" : [                {                    "id" : “SSID4343”,                    "sum" : [                        {                            "name" : "linux",                            "value" : 2                        }                    ],                    "macList" : [                        {                            "id" : “43:43:43:43:43:34”,                            "sum" : [                                {                                    "name" : "linux",                                    "value" : 2                                }                            ]                        }                    ]                }            ]        }    ]}

我正在使用golang作为使用mgo.v2包与mongoldb操纵数据的语言

预期输出为:

输出

  • Linux:12 + 2 = 14
  • ubuntu:4 + 0 = 4

不要在会场列表中考虑内部列表。

答案1

小编典典

您需要使用聚合框架,在该框架中,您将运行一个聚合管道,该管道首先venueList使用
$match
运算符根据ID 过滤集合中的文档。

第二个流水线将平整化venueListsum子文档数组,以使文档中的数据作为非规范化条目进一步在流水线下方进行处理。该
$unwind
运营商在这里很有用。

$match
展开后,有必要使用进一步的过滤器,以便仅允许您要聚合的文档进入下一个管道。

主管道将是
$group
运算符阶段,该运算符阶段使用累加器运算符聚合过滤后的文档以创建所需的总和
$sum
。为了获得理想的结果,您将需要使用诸如
$cond
创建独立计数字段的时间运算符,因为这将
$sum
根据名称值将文档数量提供给表达式。

综上所述,请考虑运行以下管道:

db.collection.aggregate([    { "$match": { "venueList.id": { "$in": ["VID1212", "VID4343"] } } },    { "$unwind": "$venueList" },    { "$match": { "venueList.id": { "$in": ["VID1212", "VID4343"] } } },    { "$unwind": "$venueList.sum" },        {        "$group": {            "_id": null,            "linux": {                "$sum": {                    "$cond": [                         { "$eq": [ "$venueList.sum.name", "linux" ] },                         "$venueList.sum.value", 0                     ]                }            },            "ubuntu": {                "$sum": {                    "$cond": [                         { "$eq": [ "$venueList.sum.name", "ubuntu" ] },                         "$venueList.sum.value", 0                     ]                }            }        }    }])

要与mGo配合使用,您可以使用http://godoc.org/labix.org/v2/mgo#Collection.Pipe中的指南转换上述管道。


要获得比上述方法执行速度快得多并且还考虑了总和列表的未知值的更灵活,性能更好的替代方法,请按以下方式运行替代管道

db.collection.aggregate([    { "$match": { "venueList.id": { "$in": ["VID1212", "VID4343"] } } },    { "$unwind": "$venueList" },    { "$match": { "venueList.id": { "$in": ["VID1212", "VID4343"] } } },    { "$unwind": "$venueList.sum" },        {         "$group": {            "_id": "$venueList.sum.name",            "count": { "$sum": "$venueList.sum.value" }        }    },    {         "$group": {            "_id": null,            "counts": {                "$push": {                    "name": "$_id",                    "count": "$count"                }            }        }    }])

Golang 和 MongoDB - 我尝试使用 golang 将切换布尔值更新为 mongodb,但得到了对象

Golang 和 MongoDB - 我尝试使用 golang 将切换布尔值更新为 mongodb,但得到了对象

golang 和 mongodb - 我尝试使用 golang 将切换布尔值更新为 mongodb,但得到了对象

问题内容

我曾经使用 React 和 Nodejs 来实现 todo 应用程序。 React 和 Nodejs 中更新 Mongodb 数据库的切换功能如下代码:

const toggleChecked = ({ _id, isChecked }) => {
  TasksCollection.update(_id, {
    $set: {
      isChecked: !isChecked
    }
  })
};
登录后复制

我想在Golang中实现切换功能来更新布尔字段,但我得到了对象,以下是golang代码:

func updateOneMovie(movieId string) model.Netflix {
    id, _ := primitive.ObjectIDFromHex(movieId)
    filter := bson.M{"_id": id}
    update := bson.M{"$set": bson.M{"watched": bson.M{"$not": "$watched"}}}
    var updateResult model.Netflix

    result, err := collection.UpdateOne(context.Background(), filter, update)

    err = collection.FindOne(context.Background(), filter).Decode(&updateResult)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(result)
    return updateResult
}
登录后复制

Mongodb 中的结果更新为对象而不是布尔值。我该如何修复以使其更新切换布尔值?

解决方法

传递单个文档(例如 bson.M或bson.D)作为更新文档,字段名称和值将按原样(字面意思)解释。

立即学习“go语言免费学习笔记(深入)”;

使用带有更新的聚合管道,您必须传递一个数组作为更新文档,这会触发将其解释为聚合管道。这是唯一的要求。该数组可能是 mongo.Pipeline, bson.A,[]bson.D, []bson.M 甚至 []any,没关系,它必须是 Go 中的数组或切片。这些元素可以是 bson.M、bson.D 或表示文档的任何其他值。

最简单的解决方案:

filter := bson.M{"_id": id}
update := []any{
    bson.M{"$set": bson.M{"watched": bson.M{"$not": "$watched"}}}
}
登录后复制

以上就是Golang 和 MongoDB - 我尝试使用 golang 将切换布尔值更新为 mongodb,但得到了对象的详细内容,更多请关注php中文网其它相关文章!

golang中如何实现MongoDB数据的修改

golang中如何实现MongoDB数据的修改

在软件开发中,数据的增删改查是比较常见的操作。作为一名后端工程师,我们需要经常地与数据库打交道。而在数据库的操作中,mongodb 是比较流行的一种数据库。

本文将着重介绍在 Golang 中如何实现 MongoDB 数据的修改。在开始之前我们需要了解以下几点:

  1. 在本地安装 MongoDB 数据库,并启动服务;
  2. 在 Golang 项目中引入 MongoDB 驱动包;
  3. 编写相应的代码实现数据的修改操作。

下面来一步步进行实现。

  1. 引入 MongoDB 驱动包

在 Golang 中,我们可以通过第三方的 MongoDB 驱动包来实现对 MongoDB 数据库的增删改查。这里我们可以使用官方的 MongoDB 驱动包 go.mongodb.org/mongo-driver 来进行操作。在代码中使用以下语句引入该包:

import "go.mongodb.org/mongo-driver/mongo"
登录后复制
  1. 连接 MongoDB 数据库

在进行任何操作之前,我们需要建立与 MongoDB 数据库的连接。在 Golang 中,可以使用如下代码实现与 MongoDB 的连接:

立即学习“go语言免费学习笔记(深入)”;

clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.NewClient(clientOptions)

if err != nil {
    log.Fatal(err)
}

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

err = client.Connect(ctx)

if err != nil {
    log.Fatal(err)
}

defer func() {
    if err = client.Disconnect(ctx); err != nil {
        log.Fatal(err)
    }
}()
登录后复制

首先,我们需要调用 options.Client() 方法构造连接选项。这里我们使用 ApplyURI() 方法指定 MongoDB 数据库所在的地址及端口。之后我们通过 mongo.NewClient() 方法创建一个 MongoDB 客户端,该客户端即可用于后续的操作。

在创建客户端后,我们可以通过调用 Connect() 方法连接 MongoDB,Connect() 方法的入参是一个 context.Context 对象,该对象用于控制连接的上下文和超时时间。如果连接成功,则会返回一个 mongo.Client 类型的对象。同时,我们在 defer 关键字后面添加了 Disconnect() 方法用于关闭 MongoDB 的连接。

  1. 更新数据

在 MongoDB 中,我们可以使用 UpdateOne() 方法来更新一条数据。UpdateOne() 方法的入参为一个 context.Context 对象、一个 bson.M 类型的 filter 对象和一个 bson.M 类型的 update 对象。其中,filter 对象用于过滤需要更新的数据,update 对象则为需要更新的数据。

下面给出一个示例代码,展示如何通过 UpdateOne() 方法进行数据更新:

collection := client.Database("test").Collection("users")
updateData := bson.M{
    "$set": bson.M{
        "username": "李白",
        "age":      33,
    },
}
filterData := bson.M{
    "username": "libai",
}

result, err := collection.UpdateOne(ctx, filterData, updateData)

if err != nil {
    log.Fatal(err)
}

fmt.Println(result)
登录后复制

在上述示例代码中,我们首先通过 client.Database() 方法获取了一个名为 test 的数据库,并在该数据库下获取了一个名为 users 的集合。之后,我们定义了一个 updateData 变量,该变量为 bson.M 类型,表示需要更新的数据。在 updateData 中我们使用了 $set 操作符,将 username 和 age 字段的值改为 "李白"、33。

接着,我们定义了一个 filterData 变量,该变量为 bson.M 类型,表示查询条件。在 filterData 中我们指定了需要更新 username 为 "libai" 的数据。

最后,我们通过 collection.UpdateOne() 方法对数据进行更新。更新成功后返回一个 mongo.UpdateResult 对象,我们可以通过该对象的相关方法获取更新的结果。

总结

本文介绍了在 Golang 中如何使用 MongoDB 驱动包实现对数据的更新操作。在实现过程中,我们需要先连接 MongoDB 数据库,再通过 UpdateOne() 方法对数据进行修改。如果您对 MongoDB 数据库的操作还不是很了解,建议您可以先学习 MongoDB 数据库的基本使用教程。

以上就是golang中如何实现MongoDB数据的修改的详细内容,更多请关注php中文网其它相关文章!

golang中的Mongodb聚合

golang中的Mongodb聚合

我有一个像这样的 mongodb集合:

{
    source: "...",url:  "...",comments: [
        .....
    ]
}

我想根据评论的数量找到前5个文件.我可以在命令提示符中使用以下查询找到所需的结果:

db.gmsNews.aggregate([
  {
     $match:{source:"..."}
  },{
     $unwind: "$comments"
  },{
     $group: {
        _id: "$url",size: {
           $sum: 1
        },}
  },{
     $sort : { size : -1 } 
  },{ 
     $limit : 5
  }
])

这给了我以下输出:

{ "_id" : "...","size" : 684 }
{ "_id" : "...","size" : 150 }

现在我想使用mgo驱动程序将此查询转换为golang.我通过以下方式使用管道:

o1 := bson.M{
        "$match" :bson.M {"source":"..."},}

o2 := bson.M{
    "$unwind": "$comments",}

o3 := bson.M{
    "$group": bson.M{
        "_id": "$url","size": bson.M{
            "$sum": 1,},}

o4 := bson.M{
    "sort": bson.M{
        "size": -1,}

o5 := bson.M{
    "$limit": 5,}

operations := []bson.M{o1,o2,o3,o4,o5}

pipe := c.Pipe(operations)

// Run the queries and capture the results
results := []bson.M{}
err1 := pipe.One(&results)

if err1 != nil {
    fmt.Printf("ERROR : %s\n",err1.Error())
    return
}

fmt.Printf("URL : %s,Size: %sn",results[0]["_id"],results[0]["size"])

不幸的是,这不起作用,我得到以下输出:

ERROR : Unsupported document type for unmarshalling: []bson.M

只是想知道我做错了什么以及如何解决这个问题.

任何帮助将受到高度赞赏.

提前致谢.

Ripul

解决方法

更改

err1 := pipe.One(&results)

err1 := pipe.All(&results)

Golang无法在MongoDB中创建文档

Golang无法在MongoDB中创建文档

golang无法在mongodb中创建文档

问题内容

我正在尝试将文档插入 mongodb,但尽管成功连接到 mongo,但我仍然收到以下错误:

http: panic serving 172.27.0.8:40176: runtime error: invalid memory address or nil pointer dereference
登录后复制

我正在初始化数据库连接的 main.go 看起来像这样

func main(){
   
      //connect to mongo
      mongoclient,err:=connecttomongo()
      if err!=nil{
          log.panic(err)
      }
      client=mongoclient
  
      //create a context that mongo needs in order to disconnect
      ctx,_:=context.withtimeout(context.background(), 15*time.second)
     // ctx,cancel:=context.withtimeout(context.background(), 15*time.second)
      //defer cancel()
      
  
      //close connection
      defer func ()  {
          if err =client.disconnect(ctx); err!=nil{
              panic(err)
          }
      }() 

    muxrouter := mux.newrouter().strictslash(true)

    //specify who''s allowed to connect
    c:=cors.new(cors.options{ 
        allowedorigins: []string{"https://*", "http://*"},
        allowedmethods: []string{"get", "post", "put", "delete", "options"},
        allowedheaders: []string{"accept", "authorization", "content-type", "x-csrf-token"},
        exposedheaders: []string{"link"},
        allowcredentials: true,
        maxage: 300,
})
    router := addroutes(muxrouter)
    handler := c.handler(router)
    log.println("service stratring at o  port ",webport)

    sterr := http.listenandserve(":9090", handler) //uncomment this line when using docker
    if sterr != nil {
        log.fatal("error starting http server :: ", err)
        return
    }

    log.println("service started at port ",webport)


    
  

}

func connecttomongo()(*mongo.client,error){
    mongousername := os.getenv("mongousername")
    mongopassword := os.getenv("mongopassword")
    //create connection options
    clientoptions:=options.client().applyuri(mongourl)
    clientoptions.setauth(options.credential{
        username: mongousername,
        password: mongopassword,
    })

    //connect
    c,err:=mongo.connect(context.todo(),clientoptions)
    if err!=nil{
        log.println("error connecting to mongo",err)
        return nil,err
    }
    log.println("connected to mongo")
    return c,nil
}
登录后复制

在一个单独的文件 models.go 中,我尝试将数据插入数据库,如下所示:

var client *mongo.Client
func  Insert(entry LogEntry)error{
    log.Printf("Attempting to insert %s", entry)
    log.Printf("client s  %s", client)
    //db:=client.Database("logs")
    //log.Printf("database  is  %s", db)
    
   collection:=client.Database("logs").Collection("logsCollection")
    log.Printf("collection is  %s", collection)

    _,err :=collection.InsertOne(context.TODO(), LogEntry{
        Name: entry.Name,
        Data: entry.Data,
        CreatedAt: time.Now(),
        UpdatedAt: time.Now(),
    })
    if err!=nil{
        log.Println("Error inserting new record into logs collection",err)
        return err
    }
    log.Println("insert successful")
    return nil
}
登录后复制

有人能发现我做错了什么吗?

立即学习“go语言免费学习笔记(深入)”;

解决方法

由于错误是通用的(例如,未提供错误的行号),我将分享一个可行的解决方案,也许可以帮助您找出问题所在。我先分享一下代码。

main.go 文件

package main

import (
    "context"
    "fmt"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type LogEntry struct {
    Name      string
    Data      string
    CreatedAt time.Time
    UpdatedAt time.Time
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
    defer cancel()

    clientOptions := options.Client().ApplyURI("mongodb://root:root@localhost:27017")
    mongoClient, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        panic(err)
    }
    defer mongoClient.Disconnect(ctx)

    demoDb := mongoClient.Database("demodb")
    myCollection := demoDb.Collection("myCollection")

    // delete documents
    if _, err := myCollection.DeleteMany(ctx, bson.M{}); err != nil {
        panic(err)
    }

    // insert data
    insertRes, err := myCollection.InsertOne(ctx, LogEntry{
        Name:      "lorem ipsum",
        Data:      "lorem ipsum",
        CreatedAt: time.Now(),
        UpdatedAt: time.Now(),
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(insertRes.InsertedID)

    // query data
    cursor, err := myCollection.Find(ctx, bson.M{})
    if err != nil {
        panic(err)
    }
    var logEntries []bson.M
    if err = cursor.All(ctx, &logEntries); err != nil {
        panic(err)
    }
    for _, v := range logEntries {
        fmt.Println(v)
    }
}
登录后复制

为了演示,我将所有逻辑放在一个文件中。在此文件中,我执行了以下步骤:

  1. 设置 mongodb 连接。
  2. 连接到数据库以及该数据库中的集合。
  3. 删除所有已有的文档(只是为了更清晰)。
  4. 在 mycollection 集合中插入新的 logentry 实例。
  5. 检索 mycollection 集合中的所有条目。

最后要提到的是我用来运行容器的 docker 命令:

docker运行-d -p 27017:27017 --name mymongo -e mongo_initdb_root_username=root -e mongo_initdb_root_password=root mongo:latest

如果您坚持使用我的解决方案,您应该能够毫无问题地插入文档。如果不是这样,请告诉我,我会尽力帮助您!

以上就是Golang无法在MongoDB中创建文档的详细内容,更多请关注php中文网其它相关文章!

关于通过在golang中检查MongoDB中的多个属性值来检索项目列表mongodb如何分析查询操作使用了哪些索引的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Golang 和 MongoDB - 我尝试使用 golang 将切换布尔值更新为 mongodb,但得到了对象、golang中如何实现MongoDB数据的修改、golang中的Mongodb聚合、Golang无法在MongoDB中创建文档的相关知识,请在本站寻找。

本文标签: