简体   繁体   中英

MongoDB: Get all elements of a nested array

Is it possible to get every element which is saved in a nested array with a find() . I need to get a list of all elements which are saved in the cat-field of the documents.

{
    "_id" : "1",
    "title" : "title 1",
    "cat" : [
        {
            "element" : "element 1"
        },
        {
            "element" : "element 2"
        }
    ]
},
{
    "_id" : "2",
    "title" : "title 2",
    "cat" : [
        {
            "element" : "element 3"
        },
        {
            "element" : "element 4"
        }
    ]
}

Result of this example should be - as I also need the id of the document:

1, element 1
1, element 2
2, element 3
2, element 4 

You can also try out following query with distinct :

db.collection.distinct("cat.element")

EDIT:

Then you can try out $map as marked in duplicate question like:

You can simply use it like :

db.collection.aggregate({
    "$project": {
    "cat": {
        "$map": {
            "input": "$cat",
            "as": "el",
            "in": "$$el.element"
        }
    },
    "title": 1
    }
})

OR

db.collection.aggregate({
    "$project": {
    "cat": {
        "$map": {
            "input": "$cat",
            "as": "el",
            "in": "$$el.element"
        }
    },
    "title": 1
    }
}, {
    $group: {
    _id: "$_id",
    "title": {
        $first: "$title"
    },
    "cat": {
        "$first": "$cat"
    }
    }
})

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