Home > database >  How to get a column of nested array
How to get a column of nested array

Time:01-06

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

CodePudding user response:

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

  •  Tags:  
  • Related