如何在 MongoDB 中查询具有未知键的 json 数组?

发布于 2025-01-15 14:05:17 字数 473 浏览 1 评论 0原文

有一个 MongoDB 数据库,其文档都是这样的:

{
    "_id": {
        "$oid": "62371a3c8200184f3b49d9e7"
    },
    "po_id": "123456",
    "po_detail": [{
        "10065": {
            "price": "123.45",
            "product": "P1"
        }
    }, {
        "11121": {
            "price": "678.90",
            "product": "P2"
        }
    }]
}

我想按“产品”(例如“P1”或“P2”)查找文档,但数组中的键(例如“10065”或“11121”)未知。

如何在 MongoDB 中查询这样的文档(使用 pymongo)?

谢谢你!

There is a MongoDB database with documents all like this:

{
    "_id": {
        "$oid": "62371a3c8200184f3b49d9e7"
    },
    "po_id": "123456",
    "po_detail": [{
        "10065": {
            "price": "123.45",
            "product": "P1"
        }
    }, {
        "11121": {
            "price": "678.90",
            "product": "P2"
        }
    }]
}

I want to find documents by "product"(such as "P1" or "P2"), but keys in array(such as "10065" or "11121") are unknown.

How to query documents like this in MongoDB(by using pymongo)?

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱你是孤单的心事 2025-01-22 14:05:17

按“产品”(例如“P1”或“P2”)查找文档不太清楚。一般来说,数据模型相当差,您应该考虑重新设计。

查询可能如下所示:

db.collection.aggregate([
  { $unwind: "$po_detail" },
  {
    $set: {
      po_detail: { $first: { $objectToArray: "$po_detail" } }
    }
  },
  { $match: { "po_detail.v.product": "P1" } },
  { $set: { po_detail: [ "$po_detail" ] } },
  { $set: { po_detail: { $arrayToObject: "$po_detail" } } }
])

Mongo Playground

find documents by "product" (such as "P1" or "P2") is not so clear. In general the data model is rather poor and you should consider a re-design.

The query could look like this:

db.collection.aggregate([
  { $unwind: "$po_detail" },
  {
    $set: {
      po_detail: { $first: { $objectToArray: "$po_detail" } }
    }
  },
  { $match: { "po_detail.v.product": "P1" } },
  { $set: { po_detail: [ "$po_detail" ] } },
  { $set: { po_detail: { $arrayToObject: "$po_detail" } } }
])

Mongo Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文