登录
首页 >  Golang >  Go问答

在 MongoDB 使用 mgo 驱动程序嵌套数组中查找特定值

来源:stackoverflow

时间:2024-03-09 22:33:26 125浏览 收藏

从现在开始,努力学习吧!本文《在 MongoDB 使用 mgo 驱动程序嵌套数组中查找特定值》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

这是我的 json 格式的 mongo 集合:

"messages" : 
{
"_id" : objectid("5c26844696b72e4b6c9ceee7"),
"pointer" : objectid("5c26844696b72e4b6c9ceee6"),
"messages" : [ 
   {
       "uuid" : "f03f7977-0b4e-11e9-9f95-144fd7c03810",
       "content" : "hello",
       "reportedtimes":0
   }, 
   {
       "uuid" : "78bb831d-0b57-11e9-a286-144fd7c03810",
       "content" : "yes",
       "reportedtimes":0
   }
  ]
}

我想从“指针”和“uuid”更新“reportedtimes”值。 我尝试了很多聚合,但没有得到这样的结果:

pipe := []bson.m{bson.m{"$match": bson.m{"pointer": knownpointer}}, {"messages": bson.m{"$match": bson.m{"uuid": knownuuid}}}, {"$inc": bson.m{"messages.$.reportedtimes": 1}}}

那个返回我不能使用“$inc”

或者那个

pipe := []bson.M{{"$match": bson.M{"pointer": knownPointer}}, {"$unwind": "$messages"}, {"$project": bson.M{"uuid": "$messages.uuid", "reportedTimes": "$messages.reportedTimes"}}, {"$match": bson.M{"uuid": knownUuid}}} then inc.

我什至没有找到我所有的尝试查询... 我完全陷入困境......我也尝试过更新(选择器,查询),但仍然找不到有效且有效的方法。 如果有一点帮助,我们将不胜感激。谢谢大家。


解决方案


这是一个简单的 Collection.Update() 操作,无需为此使用聚合:

err := c.update(bson.m{
    "pointer":       knownpointer,
    "messages.uuid": knownuuid,
}, bson.m{
    "$inc": bson.m{
        "messages.$.reportedtimes": 1,
    },
})

以下是如何设置参数以增加文档第一条消息的 reportedtimes

knownPointer := bson.ObjectIdHex("5c26844696b72e4b6c9ceee6")
knownUUID := "f03f7977-0b4e-11e9-9f95-144fd7c03810"

理论要掌握,实操不能落!以上关于《在 MongoDB 使用 mgo 驱动程序嵌套数组中查找特定值》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>