Home > Blockchain >  how to match array field and nested array field in mongodb without using unwind
how to match array field and nested array field in mongodb without using unwind

Time:03-03

My json data will look like this

{
  "videoId": 29,
  "videoComments": [
    {
      "comment": "awsome",
      "userId": 15,
      "commentTime": "2022-03-01T12:37:49.734Z",
      "userName": "user1646127068323",
      "deletedbyowner": "FALSE",
      "_id": "621e139d8e4195079c86488",
      "replyComments": [
        {
          "replyComment": "thank you",
          "replyCommentTime": "2022-03-01T12:44:53.193Z",
          "replyDeletedbyowner": "FALSE",
          "_id": "621e154557fa7045e342540"
        }
      ]
    }
  ]
}

I need to match some conditions that I mentioned below :

  1. match "videoId" == "29"
  2. then match "videoComments.deletedbyowner" == "FALSE"
  3. if I match second condition then I need to match "videoComments.replyComments.replyDeletedbyowner" == "FALSE"

I can't use unwind because my boss told me that unwind is a costly operation it will effect the app performance. so with out using unwind I need to match these conditions. could you please help out of this.

CodePudding user response:

collection_name.find(
  { videoId : 29 },
  { videoComments : { $elemMatch : { deletedbyowner : "FALSE", $elemMatch: { replyDeletedbyowner: "FALSE"} } }
).pretty();

I think this is what you are looking for. For more info check this doc

CodePudding user response:

Query

  • this keep the documents with videoId=29
  • only the elements with deletedbyowner="FALSE"
  • and only the elements with replyDeletedbyowner="FALSE"

*this is aggregate solution, we have also $elemMatch and $ to project the matched element, but here you need match on nested arrays, so i think you need aggregation, but i am not completly sure.

Test code here

aggregate(
[{"$match":{"$expr":{"$eq":["$videoId", 29]}}},
 {"$set":
  {"videoComments":
   {"$map":
    {"input":"$videoComments",
     "in":
     {"$cond":
      [{"$ne":["$$this.deletedbyowner", "FALSE"]}, null,
       {"$mergeObjects":
        ["$$this",
         {"replyComments":
          {"$filter":
           {"input":"$$this.replyComments",
            "cond":{"$eq":["$$reply.replyDeletedbyowner", "FALSE"]},
            "as":"reply"}}}]}]}}}}},
 {"$set":
  {"videoComments":
   {"$filter":
    {"input":"$videoComments", "cond":{"$ne":["$$this", null]}}}}}])
  • Related