Home > Net >  ppend an object to an array inside a nested object
ppend an object to an array inside a nested object

Time:10-10

I have a collection in MongoDB in which one of the documents looks like this:

{
  _id: ObjectId("6162883719592ea3350d3c87"),
  fullName: 'Random User',
  username: 'ruser1',
  password: 'asdadasd',
  portfolio: [ { equity: [] }, { crypto: [] }, { etf: [] }, { cash: [] } ]
}

I am trying to append a new object of the following format to the equity array inside portfolio.

Object format:

{
  name : "AAPL",
  quantity : 1,
  price : 100
}

I was trying to use the $push to do this operation, but I'm encountering the following error:

db.users.updateOne( 
{_id : ObjectId("6162883719592ea3350d3c87")},
{$push : {"portfolio.equity" : {
name : "AAPL",
quantity : 1,
price : 100
    }
  }
 }
)

MongoServerError: Cannot create field 'equity' in element {portfolio: [ { equity: [] }, { crypto: [] }, { etf: [] }, { cash: [] } ]}

I have also tried to use portfolio.$.equity, but that did not work either.

db.users.updateOne(
{_id : ObjectId("6162883719592ea3350d3c87")} , 
{$push : {"portfolio.$.equity" : {name : "AAPL", price : 100, quantity : 1}}}
)
MongoServerError: The positional operator did not find the match needed from the query.

In short, I am trying to append an object to an array inside an object's object.

How can I resolve this error or what is the appropriate way to do this?

CodePudding user response:

You can use arrayFilters with check portfolio.equity field is existed via $exists.

db.users.updateOne({
  _id: ObjectId("6162883719592ea3350d3c87")
},
{
  $push: {
    "portfolio.$[portfolio].equity": {
      name: "AAPL",
      price: 100,
      quantity: 1
    }
  }
},
{
  arrayFilters: [
    {
      "portfolio.equity": {
        $exists: true
      }
    }
  ]
})

Sample Mongo Playground

  • Related