【问题标题】:subquery replace value wrapped in list in collaction A for key in collection B mongodb子查询替换集合 A 中列表中包含的值,用于集合 B mongodb 中的键
【发布时间】:2017-11-18 10:35:45
【问题描述】:

我有一个关于 mongodb 的查询问题

我的数据库中有 2 个集合,名称为 statusmenu

status_id中的主键是menu集合中购买列表的值的外键

对于status 收藏:

{
    "_id": "green", "description": "running"
}
{
    "_id": "yellow", "description": "prepareing"
}
{
    "_id": "black", "description": "closing"
}
{
    "_id": "red", "description": "repairing"
}

对于menu 收藏:

{
    "name": "tony",
    "bought": [
        {
            "notebook": "green"
        },
        {
            "cellphone": "red"
        }
    ]
}
{
    "name": "andy",
    "bought": [
        {
            "fan": "black"
        }
    ]
}

如何查询才能得到以下答案?

(只需将description 替换为_id

{
    "name": "tony",
    "bought": [
        {
            "notebook": "running"
        },
        {
            "cellphone": "repairing"
        }
    ]
}

这是 NoSQL 的子查询问题吗?怎么用关键词去google?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    这是一个使用聚合的版本:

    我们从$unwind 阶段开始,将每个购买的商品提取到单独的行中

    然后是 $objectToArray 来规范购买的字段。

    然后我们可以执行$lookup 来加入状态。

    然后我们使用$group按名称重组

    $arrayToObject 将购买的重置为非规范化样式

    > db.menu.find()
    { "_id" : ObjectId("5a102b0b49b317e3f8d6268b"), "name" : "tony", "bought" : [ { "notebook" : "green" }, { "cellphone" : "red" } ] }
    { "_id" : ObjectId("5a102b0b49b317e3f8d6268c"), "name" : "andy", "bought" : [ { "fan" : "black" } ] }
    > db.status.find()
    { "_id" : "green", "description" : "running" }
    { "_id" : "yellow", "description" : "prepareing" }
    { "_id" : "black", "description" : "closing" }
    { "_id" : "red", "description" : "repairing" }
    > db.menu.aggregate([
    {$unwind: '$bought'}, 
    {$project: {name: 1, bought: {$objectToArray: '$bought'}}}, {$unwind: '$bought'}, 
    {$lookup: {from: 'status', localField: 'bought.v', foreignField: '_id', as: "status"}}, 
    {$project: {name: 1, bought: ["$bought.k", { $arrayElemAt: ["$status.description", 0]}]}}, 
    {$addFields: {b: {v: {$arrayElemAt: ['$bought', 1]}, k: { $arrayElemAt: ['$bought', 0]}}}}, 
    {$group: {_id: { name: '$name', _id: "$_id"}, b: {$push: "$b"}}},     
    {$project: {_id: "$_id._id", name: "$_id.name", bought: {$arrayToObject: "$b"}}}
    ])
    { "_id" : ObjectId("5a102b0b49b317e3f8d6268c"), "name" : "andy", "bought" : { "fan" : "closing" } }
    { "_id" : ObjectId("5a102b0b49b317e3f8d6268b"), "name" : "tony", "bought" : { "notebook" : "running", "cellphone" : "repairing" } }
    

    我认为它可以以更简单的方式执行,但我不知道如何(我很高兴知道)。

    【讨论】:

    • 谢谢!它对我有用。我也想知道一个更简单的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    相关资源
    最近更新 更多