MongoDB: upsert with different values for update a

2019-09-03 16:49发布

A little context: I have a document for each user that contains an array with latest 20 events related to a user. As MongoDB does not have this feature(to cap arrays inside a document), I will push my event and pop the latest one.

My problem: initializing the document(aka filling array with nulls). I want to atomically:

  • create document containing an array with 20 null values and push one value, if document does not exist

or

  • update document (push one value in array), if document exists

Do you have any other suggestions? A hack I thought about would be to declare a index with :unique and :dropDups, and to always make an initialization insert.

Related to: MongoDB fixed size array implementation

1条回答
我命由我不由天
2楼-- · 2019-09-03 17:12
登录 后发表回答