【问题标题】:Unable to fetch data from MongoDB collection using Golang无法使用 Golang 从 MongoDB 集合中获取数据
【发布时间】:2020-05-06 15:24:00
【问题描述】:

我正在尝试使用 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" : "way2chethan@live.com",
        "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 条件意味着如果所有值都在那里,那么它将根据所有值匹配记录,或者如果一些值在那里它也将匹配相应的记录。但就我而言,它根本没有获取记录。谁能帮我解决这个问题。

【问题讨论】:

    标签: mongodb go


    【解决方案1】:

    $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 }}}},
    

    【讨论】:

      猜你喜欢
      • 2012-06-04
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 2019-09-15
      • 2018-02-18
      相关资源
      最近更新 更多