0

I have a MongoDB document structure like this

{
  "_id": "002",
  "list": [
    {
      "year": "2015",
      "entries": [{...}, {...}]
    },
    {
      "year": "2014",
      "entries": [{...}, {...}]
    }
  ]
}

I want to push a new element into "entries". I know it is possible using

collection.updateOne(
    Filters.eq("_id", "002"),
    new Document("$push", new Document("list.0.entries", "{...}")
);

But this appends to "entries" of the 1st element of "list". I want to append to "entries" for the "year" 2015. How can I do this with MongoDB Java driver API (3.0)?

Stennie
  • 63,885
  • 14
  • 149
  • 175
FrankS
  • 1

2 Answers2

0

I think you should use something like

Filters.and(Filters.eq("_id", "002"), Filters.eq("list.year", "2015"))

PS As the Filters javadoc suggests, it's convenient to use static import for it (to make it less verbose by skipping the "Filters." part)

vambo
  • 851
  • 1
  • 8
  • 15
  • Still having trouble pushing the entry. collection.updateOne(and(eq("_id", "002"), eq("list.year", "2015")), new Document("$push", new Document("entries", "{...}") ); This inserts a new key "entries" with given value alongside "list", not inside "list" with "year" as 2015 – FrankS Apr 20 '15 at 01:42
  • I think (no time to try this out atm, sorry), you should use `list.$.entries` instead of "entries". See http://docs.mongodb.org/manual/reference/operator/update/positional/ . I hope that helps. – vambo Apr 20 '15 at 09:39
0

You can use

Bson filter = Filters.and(Filters.eq("_id", "002"), Filters.eq("list", Filters.eq($elemMatch, Filters.eq("year", "2015")) Document list = collection.find().filter(filter)

Afterwards you can iterate through the list to find the year 2015 and get the entries for this one and insert the new element via java code. Keep the updated list in a local variable and write this one through an update command into your mongoDB.

st.huber
  • 1,481
  • 2
  • 24
  • 45