如何在mongo中从数组中查找内容

时间:2017-01-23 09:02:14

标签: mongodb

{ 
    "_id" : ObjectId("586aac4c8231ee0b98458045"), 
    "store_code" : NumberInt(10800), 
    "counter_name" : "R.N.Electric", 
    "address" : "314 khatipura road", 
    "locality" : "Khatipura Road (Jhotwara)", 
    "pincode" : NumberInt(302012), 
    "town" : "JAIPUR", 
    "gtm_city" : "JAIPUR", 
    "sales_office" : "URAJ", 
    "owner_name" : "Rajeev", 
    "owner_mobile" : "9828024073", 
    "division_mapping" : [//this contains only 1 element in every doc
        {
            "dvcode" : "cfc", 
            "dc" : "trade", 
            "beatcode" : "govindpura", 
            "fos" : {
                "_id" : ObjectId("586ab8318231ee0b98458843"), 
                "loginid" : "9928483483", 
                "name" : "Arpit Gupta", 
                "division" : [
                    "cfc", 
                    "iron"
                ], 
                "sales_office" : "URAJ", //office
                "gtm_city" : "JAIPUR" //city
            }, 
            "beat" : {
                "_id" : ObjectId("586d372b39f64316b9c3cbd7"), 
                "division" : {
                    "_id" : ObjectId("5869f8b639f6430fe4edee2a"), 
                    "clientdvcode" : NumberInt(40), 
                    "code" : "cfc", 
                    "name" : "Cooking  & Fabric Care", 
                    "project_code" : "usha-fos", 
                    "client_code" : "usha", 
                    "agent_code" : "v5global"
                }, 
                "beatcode" : "govindpura", 
                "sales_office" : "URAJ", 
                "gtm_city" : "JAIPUR", 
                "active" : true, 
                "agency_code" : "v5global", 
                "client_code" : "USHA_FOS", 
                "proj_code" : "usha-fos", 
                "fos" : {
                    "_id" : ObjectId("586ab8318231ee0b98458843"), 
                    "loginid" : "9928483483", 
                    "name" : "Arpit Gupta", 
                    "division" : [
                        "cfc", 
                        "iron"
                    ], 
                    "sales_office" : "URAJ", 
                    "gtm_city" : "JAIPUR"
                }
            }
        }
    ], 
    "distributor_mail" : "sunil.todi@yahoo.in", 
    "project_code" : "usha-fos", 
    "client_code" : "usha", 
    "agent_code" : "v5global", 
    "distributor_name" : "Sundeep Electrical"
}

我在division_mapping数组中只有1个元素,我想找到那些在division_mapping中交换dc的文档。

我试过以下:

"division_mapping":{$elemMatch:{$eq:{"dc":"trade"}}}})

不知道我做错了什么。 //也许我必须解开阵列,但还有其他方法吗?

1 个答案:

答案 0 :(得分:0)

根据MongoDB文档

  

$elemMatch运算符匹配包含数组的文档   包含至少一个与所有指定查询匹配的元素的字段   标准。

根据上述说明,只检索div_mapping为dc的文档,请尝试执行下面提到的查询

db.collection.find({division_mapping:{$elemMatch:{dc:'trade'}}})
相关问题