检查MongoDB中数组的所有元素中是否存在字段,并返回包含该字段的文档 [英] Check if a field exists in all the elements of an array in MongoDB and return the documents that contain it

查看:800
本文介绍了检查MongoDB中数组的所有元素中是否存在字段,并返回包含该字段的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于如下示例文件

{
 "_id" : ObjectId("58f5ae159dfbbf2c98041952"),
 "patient" : {
  "drug" : [ 
 {
    "drugstartdate" : "20151007",
    "actiondrug" : "1",
    "openfda": {
     //some fields here
    }
 },
 {
  //details of one more drug that may or may not contain openfda field
 }
 ]
},
{//Second report
},.....

如何为药物阵列中的所有药物元素返回包含"openfda"子文档的文档(报告)?尝试了以下内容:

how to return documents(reports) that contain "openfda" sub-document for all the drug elements in drug array? Tried the following:

db.getCollection('collname').find({"patient.drug":
{$elemMatch:{"openfda":
{$exists:true}
}
}
})

$ elemMatch将返回至少一个药物包含"openfda"字段的所有报告.还尝试过:

$elemMatch will return all reports where atleast one drug contains "openfda" field. Also tried:

db.getCollection('BigFDAData_05_06').find({"patient.drug":
{$all:["openfda"]}})

但是上面没有返回任何内容.实现此目标的正确方法是什么?

But the above returns nothing. What is the right way to achieve this?

推荐答案

您可以使用$elemMatch查询运算符.没有直接查询运算符可以解决您的情况.

You can use $elemMatch query operator. There is no direct query operator to address your case.

db.collname.find( { "patient.drug":  { $not: { $elemMatch: { openfda: {$exists:false} } } } } )

"$elemMatch" + "$exists:false"

这部分包括patient.drug数组没有至少一个openfda嵌入式文档的所有文档.

This part includes all the documents where patient.drug array don't have at least one openfda embedded document.

$not

此部分将保留所有不在"$elemMatch" + "$exists:false"中的文档.

This part will keep the all the documents which are not in "$elemMatch" + "$exists:false".

所有具有所有drugs数组的文档都具有openfda嵌入式文档.

These are all the documents that has its all drugs array have openfda embedded doc.

这篇关于检查MongoDB中数组的所有元素中是否存在字段,并返回包含该字段的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆