mongo查询不适用于字段名称中的$

时间:2015-11-26 10:22:44

标签: mongodb nosql

获取raw_data的命令:

db.raw_data.find({'cat':'like'},
    {'properties':1}).limit(1).pretty()

数据:

{
    "_id" : ObjectId("5656b9a0c2492dec3442da52"),
    "properties" : {
        "subcategory" : "49",
        "$carrier" : "Vodafone India",
        "$radio" : "HSDPA",
        "$region" : "Gujarat",
        "$screen_width" : 375,
        "$wifi" : false,
        "mp_lib" : "iphone",
        "product_unlike_flag" : false,
        "mp_device_model" : "iPhone7,2",
        "user_id" : "4",
        "$city" : "Ahmedabad",
        "$manufacturer" : "Apple",
        "$os" : "iPhone OS",
        "brand" : "AO",
        "gender" : "Men",
        "mp_country_code" : "IN",
        "time" : 1445376786,
        "$app_release" : "0.8.0",
        "$lib_version" : "2.8.2",
        "$model" : "iPhone7,2",
        "$screen_height" : 667,
        "category" : "48",
        "$app_version" : "0.8.0",
        "$os_version" : "9.0.2",
        "itemcode" : "174",
        "source" : "Product"
    }
}

我想从这些数据中提取user_id和city。

我尝试了这些命令:

Command1:

db.raw_data.aggregate([{$group : {_id :{'user_id': "$properties.user_id","cat":"$cat","brand":"$properties.brand" } ,"num_tutorial" :{$sum:1}}} ,{ $project : {properties.$city : 1 } } ])

命令2:

db.raw_data.find({'cat':'like'},{'properties.$city':1})

给了我一个错误:

Error: error: {
    "$err" : "Can't canonicalize query: BadValue Positional projection 'properties.$city' does not match the query document.",
    "code" : 17287
}

有没有方法/查询,所以我可以从这些数据中提取用户 - 城市关系。

1 个答案:

答案 0 :(得分:1)

在糟糕的情况下,mongodb建议使用unicode相当于' $'。此方法称为$ sign escaping。

因此,您的查找查询将如下所示:

db.raw_data.find({'cat':'like'},{'properties.\uff04city':1})

希望这会有所帮助:)

结果:

 > db.collection.find({},{'properties.\uff04city':1})
   { "_id" : ObjectId("5656e09ccb0a925b3d5d16f2"), "properties" : { "$city" : "value" } }
   { "_id" : ObjectId("5656e502cb0a925b3d5d16f3"), "properties" : { "$city" : "value" } }