MongoDB Operator for filtering documents which a specific field has only specified value?

Viewed 369

I want to fetch URLs from the following collection which status field has only 400 (result must be: b and c). Does someone know any single mongoDB query operator for this?

Collection:

url, status

  a,  200
  a,  400
  b,  400
  c,  400

Collection Image:

1

Result must be:

b, c

How I want above mentioned result?

  • Include only 400 status documents
  • If URL and status are same then include only single document out of them
  • If URL is same and status is different then don't include any out of them
2 Answers

Hope i understand properly,

  • $group by url and store all in root field
db.collection.aggregate([
  {
    $group: {
      _id: "$url",
      status: {
        $push: "$status"
      },
      root: {
        $push: "$$ROOT"
      },
      count: {
        $sum: 1
      }
    }
  },
  • $match all elements that are not equal to 400 using $ne and $not for opposite match by $ne, it means equal to 400
  /** MATCH ALL HAVE 400 STATUS*/
  {
    $match: {
      "status": {
        $not: {
          $elemMatch: {
            $ne: "400"
          }
        }
      }
    }
  },
  • $unwind root variable and replace into root using $replaceRoot
  {
    $unwind: "$root"
  },
  {
    $replaceRoot: {
      newRoot: "$root"
    }
  },
  • $group by url for removing duplicates if same status, create new variable roots and store "$$ROOT"
  {
    $group: {
      _id: "$url",
      roots: {
        $first: "$$ROOT"
      }
    }
  },
  • again $replaceRoot with roots variable
  {
    $replaceRoot: {
      newRoot: "$roots"
    }
  }
])

Result:

[
  {
    "_id": 4,
    "status": "400",
    "url": "c"
  },
  {
    "_id": 3,
    "status": "400",
    "url": "b"
  }
]

Working Playground: https://mongoplayground.net/p/C6tC8ho1t6M

I recommend that you take a look at Official Documentation for 'find()'

I don't know if you use javascript or something else, but your method for filtering after the status column would look like ('test' being your collection name):

db.test.find( { "status": "400" } )

This means that your will 'find' all the values for which your status column is equal to 400 as a string

Related