0

Currently I am learning mongodb. Suppose I have one collection named post in mongodb which data is :

[{
    id: 123,
    uId: 111,
    msg: 'test 1',
    attachments: [
        {name: 'attach1', url: 'https://example.com', isDeleted: false},
        {name: 'attach2', url: 'https://example.com', isDeleted: true}
    ]
},
{
    id: 456,
    uId: 222,
    msg: 'test 2',
    attachments: [
        {name: 'attach1', url: 'https://example.com', isDeleted: true}
    ]
},
{
    id: 789,
    uId: 333,
    msg: 'test 3',
    attachments: [
        {name: 'attach1', url: 'https://example.com', isDeleted: false}
    ]
}]

Now i want the result of all post where attachments.isDeleted is false which look like :

[{
    id: 123,
    uId: 111,
    msg: 'test 1',
    attachments: [
        {name: 'attach1', url: 'https://example.com', isDeleted: false}
    ]
},
{
    id: 456,
    uId: 222,
    msg: 'test 2',
    attachments: []
},
{
    id: 789,
    uId: 333,
    msg: 'test 3',
    attachments: [
        {name: 'attach1', url: 'https://example.com', isDeleted: false}
    ]
}]

I tried this db.post.find({attachments: {$elemMatch: {isDeleted: false}}}) but it is not working. I have taken help from [https://stackoverflow.com/questions/62953855/how-get-query-for-array-of-objects-in-mongodb]

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
Saurabh
  • 3
  • 3

1 Answers1

1

I think this is what you are looking for. It uses the Mongodb aggregation framework. You can take a look the documentation to see details. In brief, the $project stage allow us select fields to show or to hide, and it admits calculated fields. We calculated a new attachments field using $filter stage with a the given condition (isDeleted equals to false).

db.collection.aggregate([
  {
    "$project": {
      _id: 1,
      uId: 1,
      msg: 1,
      attachments: {
        "$filter": {
          "input": "$attachments",
          "as": "attachment",
          "cond": {
            "$eq": [
              "$$attachment.isDeleted",
              false
            ]
          }
        }
      }
    }
  }
])

You can try it in: https://mongoplayground.net/p/YDvpkbZIZ2H

Note that I changed id by _id, but it was only for style purpose.

Hope I helped.

biorubenfs
  • 643
  • 6
  • 15