【问题标题】:basic mongodb nested sets search, only want to retrieve single value基本的mongodb嵌套集搜索,只想检索单个值
【发布时间】:2015-06-16 10:33:54
【问题描述】:

我刚开始使用基于文档的数据存储大约 3-4 小时,我有一个基本问题想了解。

{ "_id": "5527e5ae06e55c02049bd114", “所有者”:“约翰·多伊”, “客户”:[“5527e3c806e55c01dad3a132”、“5527e3c806e55c01dad3a133”、“5527e3c806e55c01dad3a134”]、 “地点” : [ { “地址”:“华尔街”, "location_id": "123123213", “小贩” : [ { “名称”:“你好 123”, “价格”:“3”, “序列号”:“000000009730978e” }, { “名称”:“你好 abc”, “价格”:“3.5”, “序列号”:“0000000097308888” } ] }, { “地址”:“PCH 1”, "location_id": "987987", “小贩” : [ { “名称”:“你好 456342”, “价格”:“4”, “序列”:“000000009733452435” }, { “名称”:“你好 sdfsdg”, “价格”:“4.5”, “序列”:“0000000095243532453” } ] } ] }

那么我怎样才能找到 location.serial.price?

db.test.find_one( {"location.location_id" : "123123213" , "location.vendor.serial" : "000000009730978e" } )

将返回整个对象,但我只对这些条件匹配的 location.serial.price 感兴趣。

非常感谢, 本

【问题讨论】:

    标签: mongodb mongodb-query pymongo nosql


    【解决方案1】:

    通常您会使用positional-operator ($) 来引用数组条目。但不幸的是,这个运算符有一个严重的限制:它不适用于嵌套数组。所以在这种情况下它对你没有帮助。

    您可以改为使用聚合管道,其中unwinds 两个数组,然后matches 串行。

    db.test.aggregate([
        // create a stream of location-documents
        { $unwind: "$location" },
        // filter the stream by location-id
        { $match: { "location.id" : "123123213" },
        // expand the remaining stream further to individual vendor-documents
        { $unwind: "$vendor" },
        // filter the stream by serial
        { $match: { "location.vendor.serial": "000000009730978e" } }
    ]);
    

    请记住,聚合可能会变得非常缓慢。它还具有每个聚合步骤 16MB 的限制。您可以使用allowDiskUse:true 选项避免该限制,但这会使其速度更慢。因此,当您有大量数据并且需要考虑性能时,您可能需要重新考虑您的数据库架构。

    【讨论】:

    • 谢谢,但我无法让它运行代码link 错误消息link
    • @BenSchmidt 尝试在比赛阶段的字段名称前不带“$”。
    【解决方案2】:

    Mongodb aggregation 在这里使用,下面的查询将满足您的条件

    db.collectionName.aggregate({
        "$unwind": "$location"
    },
    {
        "$match": {
        "location.location_id": "123123213"
        }
    },
    {
        "$unwind": "$location.vendor"
    },
    {
        "$match": {
        "location.vendor.serial": "000000009730978e"
        }
    },
    {
        "$project": {
        "serial": "$location.vendor.serial",
        "price": "$location.vendor.price",
        "_id": 0
        }
    }).pretty()
    

    【讨论】:

    • 也同意Philipp的描述aggregation也会影响性能
    • 嗨@yogesh:非常感谢,但我无法让它运行,这是我的代码link 错误消息文件“yogesh.py”,第75行,在“_id ": 0 TypeError: aggregate() 正好需要 2 个参数(给定 6 个)
    • 非常感谢!我的 mac 不断出现各种错误,在我的 linux 机器上运行良好。再次感谢
    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 2011-09-14
    • 1970-01-01
    • 2016-01-13
    相关资源
    最近更新 更多