json - 查询嵌入式文档数组给出错误答案

标签 json mongodb

我是 MongoDB 的新手。这是我的 JSON 文档

> 
> db.test.find().pretty()
{
"_id" : ObjectId("59ee168f9da785077ed9359d"),
"recordid" : 500,
"metadata" : [
    {
        "field" : 1,
        "values" : [
            100,
            102,
            110,
            151,
            804
        ]
    },
    {
        "field" : 2,
        "values" : [
            201,
            202,
            151
        ]
    },
    {
        "field" : 3,
        "values" : [
            350,
            351
        ]
    }
]
}
> 
>

我正在尝试在查询中使用 $and 运算符,以便为以下查询检索 0。但是它返回 1。 1 是正确答案,但不是我想要的。

... 
... 
> 
> db.test.find( {
...                     $and:[  
...                             {"metadata.field": 2},
...                             {"metadata.values": { $in: [654,804]}},
...                             {recordid: 500}
...                          ]
...                   }
...                ).count()
1
> 
> 

我知道它为什么返回 1 个结果。这是因为 804 的“值”存在于 field: 1 中。

我想要的是查询返回 0 个结果,因为 field: 2 在“值”字段中没有值 654 和 804(它只有 151、201 和 202)。

我做错了什么?

史蒂夫

最佳答案

您可以使用 $elemMatch运算符(operator):

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

例如:

db.test.find({
    recordid: 500,
    // only match those sub documents in the metadata array which have field=2 
    // and a score of either 654 or 804
    metadata: { $elemMatch: { field: "2", score: { $in: [654, 804] } } }
})

关于json - 查询嵌入式文档数组给出错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46894425/

相关文章:

node.js - 如何从使用 gridFS 存储的 mongodb 读取 mp3 文件?

mongodb - 选择/配置数据库以获得高吞吐量、可靠、一致的写入吞吐量,牺牲延迟

node.js - 对象不存在-Mongodb

c# - 将 Dictionary<DateTime,T> 序列化为 BSON 时出现 BsonSerializationException

javascript - 根据输入字段生成 JSON 数据

javascript - 如何打开具有特定 ID 或类的 colorbox?

javascript - 如何在 Angular 8 中使用来自 HTML 输入的 JSON 文件?

javascript - 在 JSON 中通过键和值查找对象,以防我不知道 JSON 的结构是单个、数组还是嵌套深层结构

python - 使用 pandas 和 json_normalize 来展平嵌套的 JSON API 响应

ruby-on-rails - Rails 控制台和 mongodb