Pratik Agarwal
Pratik Agarwal

Reputation: 348

Implmenting a Queue of size N in mongoose

So I have a model of chats and I want to keep only 100 messages in the messages: [] to save memory. I followed some forums but I found Capped Collection in latest articles which do not exactly meet my query.

I can use $each, $pop operations or arr.100 $exists in operations but will need to add queries (for counting messages and then popping if length > N). Can adding new messages, popping if length > N can be done in 1 query?

Is there any short query for this, or queue implementation?

Here's the model:

messageOb = mongoose.Schema({       
    _id: false,
    sender: String,
    text: String,
    time: Number,
    seen: Boolean
}, {versionKey: false});

const chatSchema = mongoose.Schema({
    _id: {type: mongoose.Types.ObjectId, require: true},
    messages: [messageOb],      // max size of array will be 100
    createdOn: Number   // new Date().getTime() 
});

Upvotes: 0

Views: 592

Answers (1)

Joe
Joe

Reputation: 28356

In MongoDB 4.2+ you can use the $slice and $concatArrays aggregation operators.

db.chats.update(
   {filter criteria},
   [{$set:{
      messages:{
        $slice:[
           {$concatArrays:["$messages",[{new message object}]]}, 
           -100
        ]
      }
   }}]
)

Upvotes: 1

Related Questions