简体   繁体   English

MongoDB从多个文档中获取子文档数组到自己的数组中

[英]MongoDB get subdocuments array from multiple documents into own array

I have the following document structure.我有以下文档结构。

{
    "_id" : "0026",
    "description" : "test",
    "name" : "test",
    "options" : [
        {
            "_id" : "002",
            "color" : true,
            "visible" : true,
            "label" : "sample",
        }, 
        {
            "_id" : "003",
            "color" : true,
            "visible" : true,
            "label" : "sample",
        }
    ],
},
{
    "_id" : "0027",
    "description" : "test",
    "name" : "test",
    "options" : [
        {
            "_id" : "001",
            "color" : true,
            "visible" : true,
            "label" : "sample",
        }, 
        {
            "_id" : "002",
            "color" : true,
            "visible" : true,
            "label" : "sample",
        }
    ],
},

I am trying to return one array of only the 'options' subdocuments that match an options label regex search.我试图返回一个仅包含与选项标签正则表达式搜索匹配的“选项”子文档的数组。

I think I'm pretty much there but I seem to getting back a separate array of options for each document, how do I return just one array of 'options'?我想我差不多在那里,但我似乎为每个文档取回了一组单独的选项,我如何只返回一个“选项”数组?

My current code is:我目前的代码是:

{
    $match: {
         options: {
            $elemMatch: {
               label: { $regex: '^sample', $options: 'i' },
            },
         },
    },
},
{ "$unwind": '$options' },
{
    $project: {
        _id: 0,
        options: 1,
    },
},

The structure I would like back is just an array of options:我想要的结构只是一组选项:

[
        {
            "_id" : "001",
            "color" : true,
            "visible" : true,
            "label" : "sample",
        }, 
        {
            "_id" : "002",
            "color" : true,
            "visible" : true,
            "label" : "sample",
        },
        {
                "_id" : "002",
                "color" : true,
                "visible" : true,
                "label" : "sample",
            }, 
            {
                "_id" : "003",
                "color" : true,
                "visible" : true,
                "label" : "sample",
            }
    ]

Ta.塔。

Always the way, you post a question then finally get the answer yourself!总是这样,你发布一个问题,然后最终自己得到答案!

Just needed to add:只需要添加:

{ $replaceRoot: { newRoot: '$options' } }

as the last step.作为最后一步。

Full answer:完整答案:

{
    $match: {
         options: {
            $elemMatch: {
               label: { $regex: '^sample', $options: 'i' },
            },
         },
    },
},
{ "$unwind": '$options' },
{
    $project: {
        _id: 0,
        options: 1,
    },
},
{ $replaceRoot: { newRoot: '$options' } },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM