草庐IT

MongoDB $ifNull 条件与 mgo

coder 2023-06-29 原文

我正在努力将查询从 mongo 控制台移植到我的 Go 代码。 我是 MongoDB 的新手,所以可能还有其他我没有考虑到的错误。

示例数据“用户”集合:

{ "_id" : ObjectId("592400188d84961b7f34b0cd"), "username" : "randomUser2", "location" : { "type" : "Point", "coordinates" : [ -17.282573, 63.755657 ] } }
{ "_id" : ObjectId("592400188d84961b7f34b0ce"), "username" : "randomUser1", "location" : { "type" : "Point", "coordinates" : [ -17.634135, 65.705665 ] } }

示例数据“newscounter”集合:

{ "_id" : ObjectId("592400188d84961b7f34b0cd"), "count" : 14 }

mongo 中的查询如下所示:

db.users.aggregate([
     { $geoNear: { 
         near: { type: "Point", coordinates: [-21.861198,64.120877] },
         distanceField: "distance",
         maxDistance: myDistance * 1000,
         spherical: true }
     },
    {
        $sort: { "distance": 1 }
    },
    {
     $lookup: {
        from: "newscounter",
        localField: "_id",
        foreignField: "_id",
        as: "news_count" }
    },
    {
        $unwind: { path: "$news_count", preserveNullAndEmptyArrays: true }
    },
    {
        $project : { 
            "id": 1,
            "username": 1,
            "distance": 1,
            "news_count": { $ifNull : ["$news_count.count", 0] }
        }
    }
])

输出是(我在这里为计算的距离场使用了随机值):

{ "_id" : ObjectId("592400188d84961b7f34b0cd"), "username" : "randomUser2", "distance" : 123, "news_count" : 14 }
{ "_id" : ObjectId("592400188d84961b7f34b0ce"), "username" : "randomUser1", "distance" : 456, "news_count" : 0 }

我遇到麻烦的部分是 $project 阶段的 $ifNull。

如何使用 mgo 包在 Go 中构建 $ifNull 行?

我试过:

"news_count": bson.M{
    "$ifNull": [2]interface{}{"$news_count.count", 0},
}

但它总是为 news_count 字段返回一个空字符串。

非常感谢任何帮助!

编辑[已解决]:

这个问题很愚蠢,我在 Go struct 中为 news_count 字段输入了错误的 type

为了完整起见,Go 中的管道是:

p := []bson.M{
        bson.M{
            "$geoNear": bson.M{
                "near":          bson.M{"type": "Point", "coordinates": center},
                "distanceField": "distance",
                "maxDistance":   maxDistance,
                "spherical":     true,
            },
        },
        bson.M{
            "$sort": bson.M{
                "distance": 1,
            },
        },
        bson.M{
            "$lookup": bson.M{
                "from":         "newscount",
                "localField":   "_id",
                "foreignField": "_id",
                "as":           "news_count",
            },
        },
        bson.M{
            "$unwind": bson.M{
                "path": "$news_count",
                "preserveNullAndEmptyArrays": true,
            },
        },
        bson.M{
            "$project": bson.M{
                "_id":      1,
                "username": 1,
                "distance": 1,
                "news_count": bson.M{
                    "$ifNull": []interface{}{"$news_count.count", 0.0},
                },
            },
        },
    }

结果结构:

type Result struct {
          ID        bson.ObjectId  `json:"id" bson:"_id"`
          Username  string         `json:"username" bson:"username"`
          Distance  int64          `json:"distance" bson:"distance"`
          NewsCount int64          `json:"news_count" bson:"news_count"`
      }

最佳答案

您的 news_count 投影有效,错误出在您尚未发布的代码中的其他地方。

查看这个完整的工作示例:

cu := sess.DB("").C("users")
cnc := sess.DB("").C("newscounter")

he := func(err error) {
    if err != nil {
        panic(err)
    }
}

he(cu.Insert(
    bson.M{
        "_id":      bson.ObjectIdHex("592400188d84961b7f34b0ce"),
        "username": "randomuser1",
        "location": bson.M{
            "type":        "Point",
            "coordinates": []interface{}{-17.634135, 65.705665},
        },
    },
    bson.M{
        "_id":      bson.ObjectIdHex("592400188d84961b7f34b0cd"),
        "username": "randomuser2",
        "location": bson.M{
            "type":        "Point",
            "coordinates": []interface{}{-17.282573, 63.755657},
        },
    },
))
he(cnc.Insert(
    bson.M{
        "_id":   bson.ObjectIdHex("592400188d84961b7f34b0cd"),
        "count": 14,
    },
))

pipe := cu.Pipe([]bson.M{
    {
        "$geoNear": bson.M{
            "near": bson.M{
                "type":        "Point",
                "coordinates": []interface{}{-21.861198, 64.120877},
            },
            "distanceField": "distance",
            "maxDistance":   123456789,
            "spherical":     true,
        },
    },
    {
        "$sort": bson.M{"distance": 1},
    },
    {
        "$lookup": bson.M{
            "from":         "newscounter",
            "localField":   "_id",
            "foreignField": "_id",
            "as":           "news_count",
        },
    },
    {
        "$unwind": bson.M{
            "path": "$news_count",
            "preserveNullAndEmptyArrays": true,
        },
    },
    {
        "$project": bson.M{
            "id":       1,
            "username": 1,
            "distance": 1,
            "news_count": bson.M{
                "$ifNull": []interface{}{"$news_count.count", 0},
            },
        },
    },
})

it := pipe.Iter()

fmt.Println()
m := bson.M{}
for it.Next(&m) {
    fmt.Println(m)
    fmt.Println()
}
he(it.Err())

输出:

map[_id:ObjectIdHex("592400188d84961b7f34b0cd") username:randomuser2 distance:227534.08191011765 news_count:14]

map[username:randomuser1 distance:266222.98643136176 news_count:0 _id:ObjectIdHex("592400188d84961b7f34b0ce")]

关于MongoDB $ifNull 条件与 mgo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44155465/

有关MongoDB $ifNull 条件与 mgo的更多相关文章

  1. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  2. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  3. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  4. ruby-on-rails - 使用包含多个关联和单独的条件 - 2

    我的Gallery模型中有以下查询:media_items.includes(:photo,:video).rank(:position_in_gallery)我的图库模型有_许多媒体项,每个都有一个照片或视频关联。到目前为止,一切正常。它返回所有media_items包括它们的photo或video关联,由media_item的position_in_gallery属性排序。但是我现在需要将此查询返回的照片限制为仅具有is_processing属性的照片,即nil。是否可以进行相同的查询,但条件是返回的照片等同于:.where(photo:'photo.is_processingIS

  5. ruby-on-rails - 在 haml View 中重构条件 - 2

    除了可访问性标准不鼓励使用这一事实指向当前页面的链接,我应该怎么做重构以下View代码?#navigation%ul.tabbed-ifcurrent_page?(new_profile_path)%li{:class=>"current_page_item"}=link_tot("new_profile"),new_profile_path-else%li=link_tot("new_profile"),new_profile_path-ifcurrent_page?(profiles_path)%li{:class=>"current_page_item"}=link_tot("p

  6. ruby-on-rails - 在具有 ActiveRecord 条件的相关模型中按字段排序 - 2

    我正在尝试按Rails相关模型中的字段进行排序。我研究的所有解决方案都没有解决如果相关模型被另一个参数过滤?元素模型classItem相关模型:classPriority我正在使用where子句检索项目:@items=Item.where('company_id=?andapproved=?',@company.id,true).all我需要按相关表格中的“位置”列进行排序。问题在于,在优先级模型中,一个项目可能会被多家公司列出。因此,这些职位取决于他们拥有的company_id。当我显示项目时,它是针对一个公司的,按公司内的职位排序。完成此任务的正确方法是什么?感谢您的帮助。PS-我

  7. ruby - 如果满足给定条件,则结束 ruby​​ 程序 - 2

    基本上,我只是试图在满足特定条件时停止程序运行其余行。unlessraw_information.firstputs"Noresultswerereturnedforthatquery"breakend然而,在程序运行之前我得到了这个错误:Invalidbreakcompileerror(SyntaxError)执行此操作的正确方法是什么? 最佳答案 abort("Noresultswerereturnedforthatquery")unlesscondition或unlessconditionabort("Noresultswer

  8. ruby-on-rails - 如果条件与 &&,是否有任何性能提升 - 2

    如果用户是所有者,我有一个条件来检查说删除和文章。delete_articleifuser.owner?另一种方式是user.owner?&&delete_article选择它有什么好处还是它只是一种写作风格 最佳答案 性能不太可能成为该声明的问题。第一个要好得多-它更容易阅读。您future的自己和其他将开始编写代码的人会为此感谢您。 关于ruby-on-rails-如果条件与&&,是否有任何性能提升,我们在StackOverflow上找到一个类似的问题:

  9. ruby - 与条件正则表达式作斗争 - 2

    我有一个简单的问题,但我无法解决这个问题。我的字符串格式为ID:dddd,具有以下正则表达式:/^ID:([a-z0-9]*)$/或者如下:ID:1234Status:232,所以用下面的正则表达式:/^ID:([a-z0-9]*)Status:([a-z0-9]*)$/现在我想制作一个可以处理两者的正则表达式。我想到的第一件事是:/^ID:([a-z0-9]*)$|^ID:([a-z0-9]*)Status:([a-z0-9]*)$/它匹配,但我正在研究条件正则表达式,并认为应该可以按照(伪代码)ifthestringcontains/Status://^ID:([a-z0-9]*)

  10. ruby - 重构条件变量赋值 - 2

    我正在做一个项目。目前我有一个相当大的条件语句,它根据一些输入参数为变量赋值。所以,我有这样的东西。ifsomeconditionx=somevalueelsifanotherconditionx=adifferentvalue...重构它的最佳方法是什么?我希望我最终会得到类似的东西x=somevalueifsomecondition||anothervalueifanothercondition这种事情有规律吗? 最佳答案 只需将赋值放在if之外即可。x=ifsomeconditionsomevalueelsifanotherc

随机推荐