如何在数组中返回嵌套文档 [英] How to return a nested document in an array

查看:59
本文介绍了如何在数组中返回嵌套文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档具有如下架构:

I have documents with a schema such as follows:

{
    "user_id": 123,
    "services":[
         {"name": "test",
          "data": ...
         },
         {"name": "test1",
          "data": ...
         },
         {"name": "test2",
          "data": ...
         }
    ]
}

我正在尝试按名称获得针对特定user_id的服务,返回的方式如下:

I'm trying to get a service by name for a specific user_id returned as follows:

{"name": "test2",
    "data": ...
}

我很难全神贯注于如何执行此操作,并且似乎不需要像这样的简单操作进行汇总,但也许我错了.我确定一个投影可以在find_one语句中使用,但是我不确定该使用什么.我正在使用电机不确定是否有帮助.

I'm having difficulty wrapping my head around how to do this and seems an aggregation shouldn't be needed for something as simple as this but maybe I'm wrong. I'm sure a projection would work in a find_one statement but I'm not sure what to use. I'm using Motor btw not sure if that helps.

我尝试过:

async def get_service_by_name(user_id, name):
    return await db.guilds.find_one({
        'user_id': 123,
        'services': {'$elemMatch': {'name': "test"}}},
        {'user_id: 0, 'services.$': 1}))

但这返回:

{"services":[{"name" : "test", "data" : "blah" }]}

那很好,因为它接近我想要的,而我需要做的只是:

And that's fine as it's close to what I want and all I'd need to do is:

service = await get_service_by_name(123, "test")
service = service['service'][0]

但是有没有办法在没有聚合的情况下像服务一样取回数据呢?如果没有,那么聚合应该是什么样子?

But is there a way to get the data back as just the service without an aggregation? And if not, then what should the aggregation look like?

修改

我想出了一个可以做到这一点的聚合方法,但是想确保没有更好的方法:

I came up with an aggregation that does this but want to make sure there's no better way:

await db.guilds.aggregate([
    {'$unwind': '$services'},
    {'$match':{
        '_id': 123,
        'services.name': "test"}},
    {'$project': {
        '_id': 0,
        'name': '$services.name',
        'data': '$services.data'}}
])

推荐答案

您需要运行 $ unwind services

You need to run $unwind to get single document from services and $replaceRoot to promote it to root level:

db.guilds.aggregate([
    {
        $match: { user_id: 123, "services.name": "test" }
    },
    {
        $unwind: "$services"
    },
    {
        $match: { "services.name": "test" }
    },
    {
        $replaceRoot: { newRoot: "$services" }
    }
])

这篇关于如何在数组中返回嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆