【问题标题】:Mongodb: Query a json-object nested in an arrayMongodb:查询嵌套在数组中的json对象
【发布时间】:2018-01-09 14:13:23
【问题描述】:

我对 mongodb 还很陌生,有一件事我现在无法解决:
假设,您有以下文件(简化版):

{
   'someKey': 'someValue',
   'array'  : [
       {'name' :  'test1',
        'value':  'value1'
       },
       {'name' :  'test2',
        'value':  'value2'
       }
    ]
}

哪个查询会返回 json-object,其中 value 等于 'value2'?

也就是说,我需要这个 json 对象:

{
    'name' :  'test2',
    'value':  'value2'
}

当然,我已经尝试了很多可能的查询,但没有一个返回正确的,例如

db.test.find({'array.value':'value2'})
db.test.find({'array.value':'value2'}, {'array.value':1})
db.test.find({'array.value':'value2'}, {'array.value':'value2'})  

有人可以帮我看看我做错了什么吗?
谢谢!

【问题讨论】:

    标签: arrays json mongodb find


    【解决方案1】:

    使用位置运算符

    db.test.find(
        { "array.value": "value2" },
        { "array.$": 1, _id : 0 }
    )
    

    输出

    { "array" : [ { "name" : "test2", "value" : "value2" } ] }
    

    使用聚合

    db.test.aggregate([
        { $unwind : "$array"},
        { $match : {"array.value" : "value2"}},
        { $project : { _id : 0, array : 1}}
    ])
    

    输出

    { "array" : { "name" : "test2", "value" : "value2" } }
    

    使用 Java 驱动程序

        MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
        DB db = mongoClient.getDB("mydb");
        DBCollection collection = db.getCollection("test");
    
        DBObject unwind = new BasicDBObject("$unwind", "$array");
        DBObject match = new BasicDBObject("$match", new BasicDBObject(
                "array.value", "value2"));
        DBObject project = new BasicDBObject("$project", new BasicDBObject(
                "_id", 0).append("array", 1));
    
        List<DBObject> pipeline = Arrays.asList(unwind, match, project);
        AggregationOutput output = collection.aggregate(pipeline);
    
        Iterable<DBObject> results = output.results();
    
        for (DBObject result : results) {
            System.out.println(result.get("array"));
        }
    

    输出

    { "name" : "test2" , "value" : "value2"}
    

    【讨论】:

      【解决方案2】:

      试试这样的 $in 操作符:

      db.test.find({"array.value" : { $in : ["value2"]}})

      【讨论】:

      • 感谢您的帮助,但不幸的是它也不起作用。如果我在终端中运行它,它会返回整个文档
      【解决方案3】:

      您可以在元素匹配中传递多个查找对象以获得确切答案。

      db.test.find({'array':{$elemMatch:{value:"value2"}})
      
      output: {'name' :  'test1','value':  'value1'}
      

      【讨论】:

        【解决方案4】:

        使用 $elemMatch 和 dot(.) 获得所需的输出

        db.getCollection('mobiledashboards').find({"_id": ObjectId("58c7da2adaa8d031ea699fff") },{ viewData: { $elemMatch : { "widgetData.widget.title" : "England" }}})
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-11-01
          • 2020-03-28
          • 2012-07-23
          • 2016-09-05
          • 2018-09-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多