简体   繁体   English

什么是正确的 MongoDB 查询以查找包含(无序列)列表中的一个或多个项目的所有文档?

[英]What is the correct MongoDB query to find all documents containing one or more item in an (unordered) list?

I am working on an API using FastAPI that interacts with a Mongo DB via Motor.我正在使用通过 Motor 与 Mongo DB 交互的 FastAPI 开发 API。 Our database contains documents on various illnesses such that look like this:我们的数据库包含有关各种疾病的文档,如下所示:

{
    "_id": {
        "$oid": "6008b21ba1285a480088ff48"
    },
    "names": ["heart_attack", "myocardial_infarction"],
    "umls": ["C0027051"],
    "risk_factors": ["smoking", "age < 45", "male", "obesity", "etc"],
    "risk_factors_umls": ["C0037369", "CXXXXXXX"],
    "symptoms_umls": ["C0008031", "etc."], # ids for symptoms 
    "is_emergency": true
}

I am looking for the correct MongoDB query syntax (ideally with a small python code example) that given a list of risk factors or symptom ids returns all illness documents containing one or more of these ids or strings.我正在寻找正确的 MongoDB 查询语法(理想情况下使用一个小的 python 代码示例),给出风险因素或症状 ID 的列表会返回包含这些 ID 或字符串中的一个或多个的所有疾病文档。

Most Illnesses have a different amount of symptoms, so the order of the ids varies from document to document.大多数疾病都有不同数量的症状,因此 id 的顺序因文档而异。

Since I'm very new to mongoDB I am not sure what the correct query would look like.由于我对 mongoDB 很陌生,我不确定正确的查询是什么样的。 I tried multiple variations of illness_collection.find() but so far I haven't been sucessful.我尝试了illness_collection.find()的多种变体,但到目前为止我还没有成功。

Thank you in advance for your help!预先感谢您的帮助!

you can do that with a combination of $or and $in operators like so:您可以使用$or$in运算符的组合来做到这一点,如下所示:

let symptomList = ["smoking", "C0008031"];

db.collection.find(
{
    $or: [
        { risk_factors: { $in: symptomList } },
        { symptoms_umls: { $in: symptomList } }
    ]

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM