使用$ where和length的MongoDB查询

时间:2015-09-18 18:54:44

标签: mongodb

使用下面的数据结构,我想获取值'location.country'的长度等于2的所有对象:

数据结构:

{
    "_id" : ObjectId("252532"),
    "date" : ISODate("2015-03-27T20:32:56.578Z"),
    "location" : {
        "country" : "BR",
        "coordinate" : [
            -8.95,
            -35.65
        ]
    },
    "type": 2
},
{
    "_id" : ObjectId("252525"),
    "date" : ISODate("2015-03-28T01:33:30.361Z"),
    "location" : {
        "country" : "Brazil",
        "coordinate" : [
            -15.816699981689453,
            -48.11669921875
        ]
    },
    "type": 2
},
{
    "_id" : ObjectId("24242"),
    "date" : ISODate("2015-03-28T01:33:30.471Z"),
    "type":1

}, ....

我尝试了以下查询,但收到了一条我不明白的错误。

db.collection.find({$where: "this.location.country.length == 2"});

Error: error: {
    "$err" : "TypeError: Cannot read property 'country' of undefined\n    at _funcs1 (_funcs1:1:43) near 'length == 2' ",
    "code" : 16722}

有人能开导我吗?

1 个答案:

答案 0 :(得分:5)

首先检查位置是否存在:

Nz(Me.my_chk = True, False)
相关问题