Mongodb:声明数组中的所有元素都有一个非null的字段

时间:2015-02-08 11:52:29

标签: mongodb mongoid

给出一个包含这样文件的集合:

任务收集文件

[
{
 "_id"=>BSON::ObjectId('54d674b64d42504b6a000000'), 
 "submissions"=>
  [{"_id"=>BSON::ObjectId('54d674b64d42504b6a010000'),    
    "grade"=>nil,    
    "user_id"=>BSON::ObjectId('54d1e2454d42503069060000')},
   {"_id"=>BSON::ObjectId('54d674b64d42504b6a020000'),       
    "grade"=>nil,            
    "user_id"=>BSON::ObjectId('54d1e2454d42503069070000')},
   {"_id"=>BSON::ObjectId('54d674b64d42504b6a030000'),    
    "grade"=>nil,    
    "user_id"=>BSON::ObjectId('54d1e2454d42503069080000')}
   ],
 },
{
 "_id"=>BSON::ObjectId('54d674b64d42504b6a100000'), 
 "submissions"=>
  [{"_id"=>BSON::ObjectId('54d674b64d42504b6a010000'),    
    "grade"=>5,    
    "user_id"=>BSON::ObjectId('54d1e2454d42503069060000')},
   {"_id"=>BSON::ObjectId('54d674b64d42504b6a020000'),       
    "grade"=>7,            
    "user_id"=>BSON::ObjectId('54d1e2454d42503069070000')},
   {"_id"=>BSON::ObjectId('54d674b64d42504b6a030000'),    
    "grade"=>nil,    
    "user_id"=>BSON::ObjectId('54d1e2454d42503069080000')}
   ],
 },
{
 "_id"=>BSON::ObjectId('54d674b64d42509b6a000000'), 
 "submissions"=>
  [{"_id"=>BSON::ObjectId('54d674b64d42504b6a010000'),    
    "grade"=>8,    
    "user_id"=>BSON::ObjectId('54d1e2454d42503069060000')},
   {"_id"=>BSON::ObjectId('54d674b64d42504b6a020000'),       
    "grade"=>7,            
    "user_id"=>BSON::ObjectId('54d1e2454d42503069070000')},
   {"_id"=>BSON::ObjectId('54d674b64d42504b6a030000'),    
    "grade"=>6,    
    "user_id"=>BSON::ObjectId('54d1e2454d42503069080000')}
   ],
 }
]

如何获取submissions数组不包含零级别的所有任务文档?

示例中的结果只包含最后一个。

我正在使用Mongoid,但我也欢迎纯粹的Mongodb查询。

1 个答案:

答案 0 :(得分:0)

使用elem_match和否定比较:

Task.where(:submissions.elem_match => { :grade.ne => nil })