登录
首页 >  Golang >  Go问答

无法通过 Golang 从 MongoDB 集合中检索数据

来源:stackoverflow

时间:2024-03-09 15:27:26 164浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《无法通过 Golang 从 MongoDB 集合中检索数据》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我尝试使用 mongodb 和 golang 根据某个过滤器值获取记录,但它返回空数据。我在下面解释我的 json 记录。

{
    "ordernumber" : "eqord/20/10001060",
    "orderstatus" : "pending",
    "ordertype" : "online",
    "comments" : "",
    "dispatchpriority" : "high",
    "customer" : {
        "customerid" : "5e4e2ee2a060bd3d31af431b",
        "customerfirstname" : "chehan",
        "customerlastname" : "kumar",
        "customermobile" : "9886688726",
        "customeralternatemobile" : "",
        "customeremail" : "[email protected]",
        "customertype" : "parent",
        "children" : [ 
            {
                "studentadmissionid" : "10021920086",
                "studnetfirstname" : "m sri ranga gayathri",
                "studentlastname" : "",
                "studentgrade" : "pu-2/12",
                "studentgender" : "female",
                "language" : "sanskrit"
            }
        ],
        "isshippingaddresssameasbillingaddress" : false,
        "storecode" : "dkfl",
        "storedescription" : "deeksha dcfl store is a place where parents can purchase all the school merchandise in one place at reasonable prices.",
        "storebranch" : "",
        "storetype" : "online",
        "storename" : "deeksha, yelahanka, bengaluru",
        "storecustomerid" : ""
    },
    "products" : [ 
        {
            "id" : 1,
            "storecode" : "dkfl",
            "storename" : "deeksha, yelahanka, bengaluru",
            "storedescription" : "deeksha dcfl store is a place where parents can purchase all the school merchandise in one place at reasonable prices.",
            "storebranch" : "talaghattapura",
            "addressline1" : "31/1, talaghattapura",
            "addressline2" : "kanakapura road",
            "street" : "vajramuneeswara temple road",
            "landmark" : "",
            "latitude" : "undefined",
            "longitude" : "undefined",
            "city" : "bengaluru",
            "state" : "karnataka",
            "country" : "india",
            "pincode" : "560062",
            "storetype" : "online",
            "warehousecode" : "",
            "description" : "",
            "productname" : "boys white & blue striped half shirt",
            "productcode" : "05t9yncon",
            "producttype" : "c",
            "brand" : "sa",
            "vendorcode" : "",
            "sku" : "dkflmshtsam38",
            "basesku" : "dkfl05t9yncon",
            "categoryid" : "",
            "categoryname" : "uniform/formal/shirts/male",
            "attributeset" : "1000000",
            "gender" : "m",
            "baseunitprice" : 452.38,
            "taxpercentage" : 5.0,
            "hsncode" : 6021,
            "baseunitofmeasure" : "",
            "weight" : 0.0,
            "taxamount" : 22.6200008392334,
            "mrp" : 475.0,
            "weightage" : "",
            "discountprice" : 475.0,
            "totalorderquantity" : 4,
            "totalproductprice" : 1900.0,
            "totalproductdiscountprice" : 1900.0,
            "minimumprice" : 0.0,
            "currencycode" : "inr",
            "minimumbuyqty" : 1,
            "maximumbuyqty" : 6,
            "totalbaseunitofmeasure" : "",
            "totalweight" : "",
            "variants" : [ 
                {
                    "name" : "sizes",
                    "value" : [ 
                        "38"
                    ],
                    "code" : [ 
                        "24", 
                        "26", 
                        "28", 
                        "30", 
                        "32", 
                        "34", 
                        "36", 
                        "38", 
                        "40", 
                        "42", 
                        "44", 
                        "46", 
                        "48"
                    ],
                    "unitofmeasure" : ""
                }, 
                {
                    "name" : "colours",
                    "value" : [ 
                        "white"
                    ],
                    "code" : [ 
                        "m"
                    ],
                    "unitofmeasure" : ""
                }, 
                {
                    "name" : "grades",
                    "value" : [ 
                        "pu-1/11"
                    ],
                    "code" : [ 
                        "u", 
                        "v"
                    ],
                    "unitofmeasure" : ""
                }
            ]
        }
    ],
    "isactive" : false,
    "focussync" : false
}

这是我的 mongodb json 格式。我在下面解释我的代码。

func SalesOrderSearch(SalesOrder *models.OrderFilterData) map[string]interface{} {
    logger.Log.Println("OrderRepository SalesOrderSearch Function Begin")
    session, error := driver.Connect()
    db := session.DB(config.Configuration.Database)
    var resp map[string]interface{}
    Status := SalesOrder.Status
    AdmissionID := SalesOrder.AdmissionID
    Grade := SalesOrder.Grade
    ProductName := SalesOrder.ProductName
    Category := SalesOrder.Category
    Branch := SalesOrder.Branch
    Vendor := SalesOrder.Vendor
    fmt.Println(AdmissionID,Grade,ProductName,Branch,Category,Vendor)
    resourceManager := resources.ResourceManager{}
    if error != nil {
        resp := utils.Message(resourceManager.GetProperty(constants.ERROR), resourceManager.GetProperty(constants.DB_SERVER_NOT_REACHABLE_CODE), resourceManager.GetProperty(constants.DB_SERVER_NOT_REACHABLE_DESC))
        return resp
    } else {
        var result []interface{}
        filter := []bson.M{
            bson.M{"$match": bson.M{"OrderStatus": Status, "Customer": bson.M{"$elemMatch":bson.M{"Children":bson.M{"$elemMatch":bson.M{"StudentAdmissionID":AdmissionID}}}},"Products":bson.M{"$elemMatch":bson.M{"ProductName":ProductName,"CategoryName":Category }}}},
            bson.M{ "$skip" : 0 },
            bson.M{ "$limit" : 5 },

        }
        err := db.C(ORDERCOLLECTION).Pipe(filter).All(&result)
        fmt.Println(err);
        if err != nil {
            resp = utils.Message(resourceManager.GetProperty(constants.ERROR), resourceManager.GetProperty(constants.CUSTOMER_SEARCH_NOTFOUND_CODE), resourceManager.GetProperty(constants.CUSTOMER_SEARCH_NOTFOUND_DESC))
        } else {
            resp = utils.Message(resourceManager.GetProperty(constants.SUCCESS), resourceManager.GetProperty(constants.CUSTOMER_SEARCH_FOUND_CODE), resourceManager.GetProperty(constants.CUSTOMER_SEARCH_FOUND_DESC))
            resp["data"] = result
        }
    }
    defer session.Close()
    return resp
}

在这里,我需要根据给定的某些过滤条件搜索记录,并且它应该是 or 条件意味着如果所有值都存在,那么它将根据所有值匹配记录,或者如果存在某些值,它也会匹配相应记录。但就我而言,它根本没有获取记录。有人可以帮我解决这个问题吗?


解决方案


$elemmatch 在匹配数组时使用,以指示多个条件应全部匹配同一元素。

您正在对 customer 字段使用 $elemmatch,该字段不包含数组,因此不会匹配 $elemmatch 运算符。

如果您匹配的字段不是数组,或者您仅指定单个字段匹配,则无需使用 $elemmatch

例如:

"children":bson.m{"$elemmatch":bson.m{"studentadmissionid":admissionid}

"children.studentadminssionid":admissionid

应该匹配相同的文档。

您与 products 数组的匹配指定了 2 个要匹配的字段,因此需要 $elemmatch

尝试:

bson.M{"$match": bson.M{"OrderStatus": Status, "Customer.Children.StudentAdmissionID":AdmissionID,"Products":bson.M{"$elemMatch":bson.M{"ProductName":ProductName,"CategoryName":Category }}}},

本篇关于《无法通过 Golang 从 MongoDB 集合中检索数据》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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