wtyork
wtyork

Reputation: 132

How to get a column of nested array

I have a document like

{_id:xxx, xyz:[[1,2,3],[1,2,3],[1,2,3]]}

Now I want to query the first column data

x:[1,1,1]

How could I do it?

I know I can make the xyz

[{x:1,y:2,z:3},{x:1,y:2,z:3},{x:1,y:2,z:3}]

and use

find({},{x:'$xyz.x'})

Upvotes: 0

Views: 64

Answers (1)

YuTing
YuTing

Reputation: 6629

db.collection.aggregate([
  {
    $set: {
      xyz: {
        "$map": {
          "input": "$xyz",
          "as": "m",
          "in": {
            x: { $first: "$$m" },
            y: { $arrayElemAt: [ "$$m", 1 ] },
            z: { $last: "$$m" }
          }
        }
      }
    }
  },
  {
    $project: {
      x: "$xyz.x"
    }
  }
])

mongoplayground


db.collection.aggregate([
  {
    $set: {
      x: {
        "$map": {
          "input": "$xyz",
          "as": "m",
          "in": {
            $first: "$$m"
          }
        }
      }
    }
  },
  {
    "$unset": "xyz"
  }
])

mongoplayground

Upvotes: 1

Related Questions