Should I use aggregate function to change data like update, delete?

I have a project going on, and I keep thinking about using aggregate function to speed up the codes because mongodb still faster than javascript right ?

Let’s say for 1 example:

{
		"_id": "6512f6fc6120ccb5a1112aef",
		"postBody": "This is a post",
		"postHeading": "Hello ",
		"views": 0,
		"images": [],
		"likes": [],
		"mode": "normal",
		"comments": [
			{
				"comment": "This is 123",
				"userId": "651129da4ab8bce719dc9b78",
				"replies": [
					{
						"comment": "This is 123",
						"userId": "651129da4ab8bce719dc9b78",
						"_id": "6517c051e3c8018bfd19c9f3"
					},
					{
						"comment": "This is 123",
						"userId": "651129da4ab8bce719dc9b78",
						"_id": "6517c059e3c8018bfd19c9f9"
					},
					{
						"comment": "This is 123",
						"userId": "651129da4ab8bce719dc9b78",
						"_id": "6517c059e3c8018bfd19ca01"
					}
				],
				"_id": "6517bf501185a06202599943"
			}
		],
		"createdAt": "2023-09-26T15:21:32.994Z",
		"updatedAt": "2023-09-30T06:29:46.239Z",
		"user": {
			"_id": "651129da4ab8bce719dc9b78",
			"username": "hoanghieu",
			"email": "hoanghieufro@gmail.com"
		},
	},

so this is my post in the posts table, Let’s say I want to add one comment in one comment’s replies, If I do javascript code only, I will have to use 1-2 for loops for it to work, now if I use the aggregate function to do so like this

const aggregatePost = (
      await this.postModel.aggregate([
        {
          $match: { _id: postId },
        },
        {
          $addFields: {
            hasComment: {
              $size: {
                $filter: {
                  input: '$comments',
                  as: 'comment',
                  cond: { $eq: ['$$comment._id', commentId] },
                },
              },
            },
          },
        },
        {
          $addFields: {
            comments: {
              $cond: {
                if: { $eq: ['$hasComment', 0] },
                then: {
                  $concatArrays: [
                    '$comments',
                    [
                      {
                        userId: userId,
                        comment: createCommentDto.commentBody,
                        _id: createdCommentId,
                        replies: [], // Initialize replies as an empty array for top-level comments
                      },
                    ],
                  ],
                },
                else: {
                  $map: {
                    input: '$comments',
                    as: 'comment',
                    in: {
                      $cond: {
                        if: { $eq: ['$$comment._id', commentId] }, // Replace '$someCommentId' with the actual comment ID
                        then: {
                          // Add a reply to the matching comment
                          $mergeObjects: [
                            '$$comment',
                            {
                              replies: {
                                $concatArrays: [
                                  '$$comment.replies',
                                  [
                                    {
                                      userId: userId,
                                      comment: createCommentDto.commentBody,
                                      _id: createdCommentId,
                                    },
                                  ],
                                ],
                              },
                            },
                          ],
                        },
                        else: '$$comment', // Keep the original comment if it doesn't match
                      },
                    },
                  },
                },
              },
            },
          },
        },
      ])
    )[0];
return this.postModel.findByIdAndUpdate(postId, post);

if I do update like this, will codes run faster ? and is this worth it ? I think using aggregate function is simply to complicated, but if the speed wise is huge then I will continue using it. thank you !

I think you are in the best position to answer that. You have the code, you have the data. you simply test and time it and you will know.

but as general rule, doing things on the server is faster

1 Like

you mean in Nodejs or in mongodb will be faster ? the term “server” is kinda vague to be honest. But thanks, I guess I have to do it on my own then.

on the database server