# 查询数组。此时你可能会使用到$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({'fruit.1':'orange'})
{ "_id" : 2, "fruit" : [ "apple", "orange", "peach" ] }
# 可以按照数组长度进行查询,只查询数组长度为x的文档。
db.tianyc04.find({fruit:{$size:3}})
{ "_id" : 1, "fruit" : [ "apple", "banana", "peach" ] }
{ "_id" : 2, "fruit" : [ "apple", "orange", "peach" ] }
{ "_id" : 3, "fruit" : [ "orange", "banana", "peach" ] }
# 如果数组中存储的不是简单的字符串,可以使用$elemMatch查询,但是$elemMatch的局限性是只能返回数组中的第一个匹配记录。
db.tianyc05.find()
{ "_id" : 1, "fruit" : [ {"id":1, "name":"apple"}, {"id":2, "name":"banana"}, {"id":3, "name":"peach"} ] }
{ "_id" : 2, "fruit" : [ {"id":1, "name":"apple"}, {"id":4, "name":"orange"}, {"id":3, "name":"peach"} ] }
{ "_id" : 3, "fruit" : [ {"id":4, "name":"orange"}, {"id":2, "name":"banana"}, {"id":3, "name":"peach"} ] }
db.tianyc05.find({fruit:{$elemMatch:{id:2}}});