Inserting an element into an Array within an Array in a MongoDB Collection

Hi,

I have a MongoDB collection containing entities of type SessionGroupEntity.

Each sessionGroup contains Sessions,
and each session can contain Bookmarks.
Note that sessionGroup ids are unique across the entire collection.
SessionIds are unique across all sessionGroups.

Following is a pseudo model:

public class SessionGroupEntity {
    private ObjectId id;
    private String tenantId;
    private List<SessionEntity> sessions;
}

public class SessionEntity {
    String sessionId;
    private Instant creationTime;
    private SessionStatus status;
    private List<BookmarkEntity> bookmarks;
}

public class BookmarkEntity {
    private String bookmarkId;
    private Instant timestamp;
    private String title;
    private String description;
}

Initially we populate the collection with a SessionGroup with one or more Sessions in it,
yet without any Bookmarks in any of the sessions.

Later we would like to add bookmarks into a specific session within a specific sessionGroup.

We are using Spring data MongoTemplate, and MongoDB 4.0.2
Following is the code I run:

    public boolean addBookmark(String tenantId, String sessionId, String sessionGroupId, BookmarkEntity entity) {

        Update update = new Update()
            .push("sessions.$[session].bookmarks", entity)
            .filterArray(Criteria.where("sessions.sessionId").is(sessionId));

        Query query = queryByTenantIdSessionIdAndSessionGroupId(tenantId, sessionId, sessionGroupId);
        UpdateResult status = mongoTemplate.updateFirst(query, update, SessionGroupEntity.class);
        return status.getModifiedCount() > 0;
    }

Result:

The update fails with an exception:

com.mongodb.MongoWriteException: No array filter found for identifier ‘session’ in path ‘sessions.$[session].bookmarks’"}

Can somebody point out what I am doing wrong?

Thanks in advance!

I forgot to add the query code:

    private Query queryByTenantIdSessionIdAndSessionGroupId(String tenantId, String sessionId, String sessionGroupId) {
        return Query.query(
            Criteria.where("_id").is(new ObjectId(sessionGroupId))
                .and("sessions.sessionId").is(sessionId)
                .and("tenantId").is(tenantId));
    }

The issue is resolved. There was a typo. The “$push” used “$[session]” while the arrayFilter used “sessions”.
A fix:

Update update = new Update()
            .push("sessions.$[session].bookmarks", entity)
            .filterArray(Criteria.where("session.sessionId").is(sessionId));```
2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.