mongo-查询(5)——查询数组
查询数组。此时你可能会使用到$all、$size。
> db.tianyc04.find()
{ "_id" : 1, "fruit" : [ "apple", "banana", "peach" ] }
{ "_id" : 2, "fruit" : [ "apple", "orange", "peach" ] }
{ "_id" : 3, "fruit" : [ "orange", "banana", "peach" ] }
#通过全匹配,查询第一行
> db.tianyc04.find({fruit:["apple", "banana", "peach"]})
{ "_id" : 1, "fruit" : [ "apple", "banana", "peach" ] }
#如果将数组中的顺序颠倒,则第一行就匹配不上了。此时可以使用$all
> db.tianyc04.find({fruit:["apple", "peach", "banana"]})
> db.tianyc04.find({fruit:{$all:["apple", "peach", "banana"]}})
{ "_id" : 1, "fruit" : [ "apple", "banana", "peach" ] }
#也可以只输入一个元素进行查询
> db.tianyc04.find({fruit:'apple'})
{ "_id" : 1, "fruit" : [ "apple", "banana", "peach" ] }
{ "_id" : 2, "fruit" : [ "apple", "orange", "peach" ] }
#如果这个元素变成了数组,mongo就会进行精确匹配。此时你可能需要使用$all进行模糊匹配:
> db.tianyc04.find({fruit:['apple']})
> db.tianyc04.find({fruit:{$all:['apple']}})
{ "_id" : 1, "fruit" : [ "apple", "banana", "peach" ] }
{ "_id" : 2, "fruit" : [ "apple", "orange", "peach" ] }
#还可以按照数组中指定位置的元素进行查询,注意数组下标的起始编号是0。
> db.tianyc04.find()
{ "_id" : 1, "fruit" : [ "apple", "banana", "peach" ] }
{ "_id" : 2, "fruit" : [ "apple", "orange", "peach" ] }
{ "_id" : 3, "fruit" : [ "orange", "banana", "peach" ] }
> db.tianyc04.find({'fruit.1':'orange'})
{ "_id" : 2, "fruit" : [ "apple", "orange", "peach" ] }
#可以按照数组长度进行查询,只查询数组长度为x的文档。
> db.tianyc04.find()
{ "_id" : 1, "fruit" : [ "apple", "banana", "peach" ] }
{ "_id" : 2, "fruit" : [ "apple", "orange", "peach" ] }
{ "_id" : 3, "fruit" : [ "orange", "banana", "peach" ] }
{ "_id" : 4, "fruit" : [ "apple" ] }
> db.tianyc04.find({fruit:{$size:3}})
{ "_id" : 1, "fruit" : [ "apple", "banana", "peach" ] }
{ "_id" : 2, "fruit" : [ "apple", "orange", "peach" ] }
{ "_id" : 3, "fruit" : [ "orange", "banana", "peach" ] }
> db.tianyc04.find({fruit:{$size:1}})
{ "_id" : 4, "fruit" : [ "apple" ] }
>