首页 文章

按数组类型查询 - MongoDB

提问于
浏览
1

我必须按类型查询我的mongoDB集合 .
假设我有 hello 集合的这两个文件:

{
        "_id" : ObjectId("56684ee0f597654b99d0d636"),
        "name" : "Scrooge",
        "surname" : "McDuck",
        "address" : {
                "road" : "Money Bin",
                "number" : 19
        },
        "hobbies" : [
                "money",
                "food",
                "cooking"
        ]
}
{
        "_id" : ObjectId("66684ee0f597654b99d0d636"),
        "name" : "Mickey",
        "surname" : "Mouse",
        "address" : {
                "road" : "Topolinia",
                "number" : 34
        },
        "hobbies" : [
                "minnie",
                "cheese"
        ]
}

现在,如果我按数组类型查询:

db.hello.find({hobbies: {$type: 4 }})

我输出中没有任何文件 . 如您所见here 4是数组类型的数量 .

4 回答

  • 2

    这是预期的行为 . 您可以使用"dot notation"$exists运算符来执行此操作

    db.hello.find({ 'hobbies.0': { '$exists': true } } )
    

    另一种方法是使用聚合和MongoDB 3.2中提供的$isArray运算符 . 但这效率较低,因为$redact进行了集合扫描 .

    db.hello.aggregate([ 
        { "$redact": { 
            "$cond": [
                 { $isArray: "$hobbies" }, 
                 "$$KEEP", 
                 "$$PRUNE" 
            ]
        }}
    ])
    
  • 1

    根据the docs,您需要使用where子句:

    db.hello.find( { $where : "Array.isArray(this.hobbies)" } );
    
  • 2

    您需要使用 where 子句 . 请参考以下语法:
    db.hello.find( { $where : "Array.isArray(this.hobbies)" } );

  • 2

    https://docs.mongodb.org/v3.0/reference/operator/query/type/#arrays

    数组当应用于数组时,$ type匹配任何指定类型的内部元素 . 如果没有投影,这意味着如果任何元素具有正确的类型,整个数组将匹配 . 通过投影,结果将仅包括所请求类型的那些元素 .

    当您在 hobbies 字段上查询时,查询将实际尝试匹配字段内的元素,因为它是一个数组 . 所以你可以这样做:

    db.hello.find({ $where: 'Array.isArray(this.hobbies)' });
    

    但它不会非常有效,也不会使用索引 .

相关问题