【问题标题】:How to Find the matched record in mongodb?如何在mongodb中找到匹配的记录?
【发布时间】:2011-11-25 03:28:15
【问题描述】:

我的收藏中有一条记录,我想获取 id 为 1 的人的详细信息。但我获取的详细信息是 2 次而不是 1 次。

    db.mycollection.insert({"person" : [ { "id":1, "details" : { "name" : "Aswini", "Age" : 10 }}, { "id":2, "details" : { "name" : "Mahesh", "Age" : 11}}]})

然后运行

    > db.mycollection.findOne({"person.id":1},{"person.details":1,"_id":0})

结果是:

    {
        "person" : 
                [
                    {
                        "details" : 
                        {
                         "name" : "Aswini",
                         "Age" : 10
                        }
                    },
                    {
                        "details" : 
                        {
                         "name" : "Mahesh",
                         "Age" : 11
                        }
                    }
                ]
    }

但我需要如下:

    {
    "person" : [
                {
                "details" : {
                            "name" : "Aswini",
                            "Age" : 10
                        }
                }
            ]
    }

不明白哪里出错了。请需要你的帮助。我正在使用 MongoDB,Java

【问题讨论】:

    标签: java mongodb find


    【解决方案1】:

    person 是一个数组。如果你想得到这个数组的第一个元素,你应该使用$slice

    db.mycollection.findOne({"person.id":1},{"person":{$slice:[0,1]},"_id":0})
    

    【讨论】:

    • 它错了。 op 不想要第一个元素,他想检索匹配的子数组,而不管位置如何。如果 person.id 子文档位于上述查询的最后一个位置,则不会发生
    • 你是绝对正确的。我想要子数组而不管它的索引。如果您有任何解决方案,请帮忙,我是 mongodb 的新手
    【解决方案2】:

    这是过滤多层嵌入文档的行为,通常匹配过滤器会返回整个文档,而不是子集。

    通常positional operator $用于匹配updates中的子文档。但是该功能尚未在返回说明符中实现。

    mongo Support for positional ($) operator in fields to return specifier 中已经存在一个悬而未决的问题。 (如果您确实需要该功能,请登录投票)

    所以你必须重新设计你的架构来处理这个问题,可能是这样的

    db.test.insert({"person" : [ { "id":1, "details" : { "name" : "Aswini", "Age" : 10 }}]})
    db.test.insert({"person" : [ { "id":2, "details" : { "name" : "Mahesh", "Age" : 11}}]})
    
    db.test.find({"person.id":1},{'person.details':1})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多