mongodb $all操作符

$all操作符帮助选择collection中field是array类型的,且该array包含所有指定的元素的document。 若使用$all操作符,语法如下:

 

{ <field>: { $all: [ <value1> , <value2> ... ] } }

 

使用例子如下

 

> db.dbdao_col.insert({_id:1,"a":1,"b":[3]});
WriteResult({ "nInserted" : 1 })
> db.dbdao_col.insert({_id:11,"a":"5","b":[5,3,7]});
WriteResult({ "nInserted" : 1 })
> db.dbdao_col.insert({_id:111,"a": 1 ,"b":[3,5]});
WriteResult({ "nInserted" : 1 })
> db.dbdao_col.insert({_id:12,"a": "5" ,"b":["alpha",5]});
WriteResult({ "nInserted" : 1 })

> db.dbdao_col.find();
{ "_id" : 1, "a" : 1, "b" : [ 3 ] }
{ "_id" : 11, "a" : "5", "b" : [ 5, 3, 7 ] }
{ "_id" : 111, "a" : 1, "b" : [ 3, 5 ] }
{ "_id" : 12, "a" : "5", "b" : [ "alpha", 5 ] }


> db.dbdao_col.find({"b": { "$all" : [5,3]}});
{ "_id" : 11, "a" : "5", "b" : [ 5, 3, 7 ] }
{ "_id" : 111, "a" : 1, "b" : [ 3, 5 ] }
> 
> 
> db.dbdao_col.find({"b": { "$all" : [3,5]}});
{ "_id" : 11, "a" : "5", "b" : [ 5, 3, 7 ] }
{ "_id" : 111, "a" : 1, "b" : [ 3, 5 ] }

> db.dbdao_col.insert({_id:1,"a":1,"b":[3]});
WriteResult({ "nInserted" : 1 })
> db.dbdao_col.insert({_id:11,"a":"5","b":[5,3,7]});
WriteResult({ "nInserted" : 1 })
> db.dbdao_col.insert({_id:111,"a": 1 ,"b":[3,5]});
WriteResult({ "nInserted" : 1 })
> db.dbdao_col.insert({_id:12,"a": "5" ,"b":["alpha",5]});
WriteResult({ "nInserted" : 1 })

> db.dbdao_col.find();
{ "_id" : 1, "a" : 1, "b" : [ 3 ] }
{ "_id" : 11, "a" : "5", "b" : [ 5, 3, 7 ] }
{ "_id" : 111, "a" : 1, "b" : [ 3, 5 ] }
{ "_id" : 12, "a" : "5", "b" : [ "alpha", 5 ] }


> db.dbdao_col.find({"b": { "$all" : [5,3]}});
{ "_id" : 11, "a" : "5", "b" : [ 5, 3, 7 ] }
{ "_id" : 111, "a" : 1, "b" : [ 3, 5 ] }
> 
> 
> db.dbdao_col.find({"b": { "$all" : [3,5]}});
{ "_id" : 11, "a" : "5", "b" : [ 5, 3, 7 ] }
{ "_id" : 111, "a" : 1, "b" : [ 3, 5 ] }

 

 

$all 其实等价于$and操作符的这种用法,但是写起来太繁琐:

 

> db.dbdao_col.find({ $and:[ {"b":3},{"b":5}]});
{ "_id" : 11, "a" : "5", "b" : [ 5, 3, 7 ] }
{ "_id" : 111, "a" : 1, "b" : [ 3, 5 ] }


> db.dbdao_col.find({ $and:[ {"b":5},{"b":3}]});
{ "_id" : 11, "a" : "5", "b" : [ 5, 3, 7 ] }
{ "_id" : 111, "a" : 1, "b" : [ 3, 5 ] }

Comment

*

沪ICP备14014813号-2

沪公网安备 31010802001379号