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]

2
  • what you have tried so far? what's your current query? Commented Jul 1, 2022 at 13:09
  • I tried this db.post.find({attachments: {$elemMatch: {isDeleted: false}}}) but it was not giving as expected result. Commented Jul 1, 2022 at 13:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.