简体   繁体   中英

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' } },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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