I have only one collection in my Mongodb and that is as follows
[
{
"_id": {
"timestamp": 1626753855,
"date": "2021-07-20T04:04:15.000+00:00"
},
"metadata": [
{
"country": "Canada",
"authors": [
{
"author": "Test Author",
"Books": [
{
"name": "Sample Book",
"code": "JCAR"
}
]
}
]
}
]
}
]
The method I am using is as follows
private void updateAuthorsMetadata(AuthorMetadata authorMetadata) {
MongoCollection<Document> collection = mDatabase.getCollection(authorMetadataCollection);
Bson eqFilter = eq("metadata.country", "Canada");
FindIterable<Document> itrDoc = collection.find(eqFilter);
if (itrDoc.first() == null) {
Document document = new Document();
document.append("metadata",
Arrays.asList(new Document("country", authorMetadata.getCountry()).append("authors",
Arrays.asList(new Document("author", authorMetadata.getAuthorName()).append("Books",
Arrays.asList(new Document("name", authorMetadata.getBookName()).append("code",
authorMetadata.getBookCode())))))));
collection.insertOne(document);
} else {
Bson andFilter = and(eq("metadata.country", "Canada"),
eq("metadata.authors.author", "John Doe"));
FindIterable<Document> itrAndDoc = collection.find(docFilter);
if (itrAndDoc.first() == null) {
Document doc = new Document("author", "John Doe).append("Books",
Arrays.asList(new Document("name", "Some Book").append("code",
"SBD4")));
Bson update = push("metadata[].authors", doc);
UpdateResult result = collection.updateOne(eqFilter, update);
}
}
}
The issue I am facing is that when I update collection at
else block
then it is adding the document to the root instead of adding it to the authors array, as shown in the image below.
How I can update it at the proper location i.e. adding to "authors" array? I am using Java driver v-3.12.7.