nicholaswmin
nicholaswmin

Reputation: 22949

MongoDB push into nested array without using indices

I'm looking to $push something into a nested array, of which the parent array matches a simple property condition:

Here's how my document looks:

{
  name: "Foo",
  boardBucket: {
    currentBoardId: 1234,
    items: [ <- looking to push into `boardItems` of an `item` in this Array
      { 
        boardId: 1234, <- that has `boardId: 1234` 
        boardItems: [ "barItem", "deyItem" ] <- Final Array I want to push to
      }
    ]
  }
}

So I'd like to push "fooItem" in boardItems of item that has boardId: 1234

Option 1: I can use dot notation and access by index

I can certainly do a $push by using dot.notation which uses the index of the item like so:

this.update({ '$push': {"boardBucket.items.0.boardItems": "fooItem" } });

But what if I don't know the index?

How can I push into boardItems of item with boardId: 1234 without using the indices (using the boardId instead)?


Note:

Upvotes: 2

Views: 1747

Answers (2)

Filip Lauc
Filip Lauc

Reputation: 3029

I think this should do the trick:

this.update(
  {"boardBucket.items": {$elemMatch: { boardId: "1234"}}},
  {'$push': {"boardBucket.items.boardItems": "fooItem" }}
);

Upvotes: 3

Cetin Basoz
Cetin Basoz

Reputation: 23797

(Sorry for not sampling in the first place, was on a rush then)

db.myDb.insert({
  name: "Foo",
  boardBucket: {
  currentBoardId: 1234,
    items: [ 
      { 
        boardId: 1234, 
        boardItems: [ "barItem", "deyItem" ] 
      },
      { 
        boardId: 1235, 
        boardItems: [ "dontPushToThisOne" ] 
      }
    ]
  }
});

db.myDb.insert({
  name: "Foo2",
  boardBucket: {
    currentBoardId: 1236,
    items: [ 
      { 
        boardId: 1236, 
        boardItems: [ "dontPushToThisOne" ] 
      }
    ]
  }
});


db.myDb.update( 
   { "boardBucket.currentBoardId":1234,
     "boardBucket.items.boardId":1234},
   { "$push" : {"boardBucket.items.$.boardItems":"fooItem"} }, {multi:1} );

Upvotes: 2

Related Questions