Home > Net >  How can I filter document in mongodb?
How can I filter document in mongodb?

Time:10-29

I have a query collection in mongodb which contains document in the below format :

{
    _id : ObjectId("61aced92ede..."),
    query : "How to solve...?",
    answer : []
    is_solved : false
}

Now, I want to filter the documents with the following condition

  1. filter all documents that are not solved. (is_solved : true)

  2. filter "n" number of document that are solved.

So, That result will have all unsolved documents and only 10 solved documents in an array.

CodePudding user response:

You can use this aggregation query:

  • First use $facet to create two ways: The document solved, and document not solved.
  • Into each way do the necessary $match and $limit the solved documents.
  • Then concatenate the values using $concatArrays.
db.collection.aggregate([
  {
    "$facet": {
      "not_solved": [
        {
          "$match": {
            "is_solved": false
          }
        }
      ],
      "solved": [
        {
          "$match": {
            "is_solved": true
          }
        },
        {
          "$limit": 10
        }
      ]
    }
  },
  {
    "$project": {
      "result": {
        "$concatArrays": [
          "$not_solved",
          "$solved"
        ]
      }
    }
  }
])

Example here where I've used $limit: 1 to see easier.

Also, if you want, you can add $unwind at the end of the aggregation to get values at the top level like this example

  • Related