【问题标题】:How to find document matching the value in array type field in Mongodb [duplicate]如何在Mongodb中查找与数组类型字段中的值匹配的文档[重复]
【发布时间】:2019-06-11 07:57:00
【问题描述】:
{      
    "_id" : ObjectId("5b98e5d17d542a2560ec026d"), 
    "RequestID" : "1536746958",     
    "JSON_Request" : [2,"1536746958","Heartbeat",{}],    
    "JSON_Response" : [3,"1536746958",{"currentTime":"2018-09-12T10:09:21.435Z"}] 
}

想要获取“JSON_Request”字段中包含“心跳”的文档

【问题讨论】:

    标签: json mongodb


    【解决方案1】:

    请试试这个db.getCollection('request').find({JSON_Request: 'Heartbeat'}) MongoDb 4.x

    或者 MongoDb 3.6 db.getCollection('request').find({ JSON_Request: { $elemMatch: {$eq: 'Heartbeat'} }}) 也检查 elemMatch MongoDb 3.6

    【讨论】:

    • 已经试过了,没有得到任何东西
    • 您是否使用了正确的收藏名称?我已经在本地试过了,上面的命令效果很好
    • 是的,我使用了正确的集合名称。不过谢谢。
    • 您的 MongoDB 版本是多少?
    • Mongodb 3.6.0版
    【解决方案2】:

    您可以使用 MongoDB 的 $in 运算符。官方文档链接:Click

    示例: 我在 queryAns 集合中有两个文档

    db.queryAns.find({}).pretty()
    
    {
        "_id" : ObjectId("5b98e5d17d542a2560ec026d"),
        "RequestID" : "1536746958",
        "JSON_Request" : [
            2,
            "1536746958",
            "Heartbeat1",
            {
    
            }
        ],
        "JSON_Response" : [
            3,
            "1536746958",
            {
                "currentTime" : "2018-09-12T10:09:21.435Z"
            }
        ]
    }
    {
        "_id" : ObjectId("5b98e5d17d542a2560ec024d"),
        "RequestID" : "1536746958",
        "JSON_Request" : [
            2,
            "1536746958",
            "Heartbeat",
            {
    
            }
        ],
        "JSON_Response" : [
            3,
            "1536746958",
            {
                "currentTime" : "2018-09-12T10:09:21.435Z"
            }
        ]
    }
    

    并且只过滤掉“JSON_Request”中包含“Heartbeat”的结果,

    db.queryAns.find({"JSON_Request": {$in: ["心跳"]}}).pretty()

    {
        "_id" : ObjectId("5b98e5d17d542a2560ec024d"),
        "RequestID" : "1536746958",
        "JSON_Request" : [
            2,
            "1536746958",
            "Heartbeat",
            {
    
            }
        ],
        "JSON_Response" : [
            3,
            "1536746958",
            {
                "currentTime" : "2018-09-12T10:09:21.435Z"
            }
        ]
    }
    

    【讨论】:

      【解决方案3】:

      像这样尝试$elemMatch

      collection.find({ JSON_Request: { $elemMatch: { $eq: "Heartbeat" } } })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-17
        相关资源
        最近更新 更多