mongoDB

MongoDB读取文档之数组操作符

2020-09-14  本文已影响0人  AbstractCulture

首先,为了方便demo,我们需要创建包含数组和嵌套数组的文档

db.accounts.insert([
    {
       name: "spring",
       balance: 8787,
       contact: ["China","Java","FrameWork"]
    },
    {
        name: "mysql",
        balance: 8,
        contact: [ ["oracle"],"database","8.0" ]
    },
    {
        name: "java",
        balance: 8,
        contact: [ ["oracle"],"core","8.0" ]
    }
])

数组操作符

$all

匹配数组字段中包含的所有查询值的文档

{ <field>: { $all: [ <value1] , <value> , ... ] } }
db.accounts.find( { contact: { $all: ["China", "Java"] } } )
db.accounts.find( { contact: { $all: [ ["oracle"] ] } } )

$elemMatch

匹配数组字段中至少存在一个值满足筛选条件的文档

{ <field>: { $elemMatch: { <query1] , <query2> , ... } } }
db.accounts.find( { contact: {$elemMatch: { $lt: "9.0", $gt: "7.0" } } } )
db.accounts.find( {
    contact: {
            $elemMatch: {
                $lt: "9.0",
                $gt: "7.0"
            },
            $all: [ ["oracle"] ]
        }
} )
db.accounts.find( {
    contact: {
            $all: [
                 { $elemMatch: { $lt: "9.0", $gt: "7.0" } },
                 { $elemMatch: { $lt: "10.0", $gt: "9.0" } },
            ]
        }
} )
上一篇下一篇

猜你喜欢

热点阅读