mehdi parastar
mehdi parastar

Reputation: 827

how to project field in array with mongodb

my collection in mongo db like this:

{
    name:"mehdi",
    grades:
        [
            {
                a:1,
                b:[2,3,4],
                c:3,
                d:4,
                e:5
            },
            {
                a:11,
                b:[22,33,44],
                c:33,
                d:44,
                e:55
            }
         ]
}

I want to get a result with project op to give me a specific field in an array like this:

{
    name:"mehdi",
    grades:
        [
            {
                a:1,
                b:2
            },
            {
                a:11,
                b:22
            }
         ]
}

how can I do this?

Upvotes: 1

Views: 33

Answers (1)

mickl
mickl

Reputation: 49945

You can use $map to select a,b fields using $type to determine whether it's an array or number:

db.collection.aggregate([
    {
        $project: {
            grades: {
                $map: {
                    input: "$grades",
                    in: {
                        a: { $cond: [ { $eq: [ { $type: "$$this.a" }, "array" ] }, { $arrayElemAt: [ "$$this.a", 0 ] }, "$$this.a" ] },
                        b: { $cond: [ { $eq: [ { $type: "$$this.b" }, "array" ] }, { $arrayElemAt: [ "$$this.b", 0 ] }, "$$this.b" ] },
                    }
                }
            }
        }
    }
])

Mongo Playground

Upvotes: 1

Related Questions