Search code examples
mongodbmongoosemongodb-querymongoose-schema

Conditional check column value in mongodb


I have document like below

 [
    {
        "_id" : ObjectId("601992e354787877866"),
        "status" : 1,
        "user_id" : 2,
    
    },
    {
        "_id" : ObjectId("601992e354787877866"),
        "status" : 2,
        "user_id" : 2,
    
    },
    {
        "_id" : ObjectId("601992e354787877866"),
        "status" : 2,
        "user_id" : 3,
    
    },
     {
        "_id" : ObjectId("601992e354787877866"),
        "status" : 3,
        "user_id" : 4,
    
    }
    ]

status column can have value 1, 2 or 3. I want to match user_id only if status column value is 2 and document having status other than 2 will come in result as it is.

I have tried with match query

 db.collection.find({"status" : 1});

But it will only match the status

Now if my user id is 2 then output should b

[
     {
            "_id" : ObjectId("601992e354787877866"),
            "status" : 1,
            "user_id" : 2,
        
        },
        {
            "_id" : ObjectId("601992e354787877866"),
            "status" : 2,
            "user_id" : 2,
        
        },
         {
            "_id" : ObjectId("601992e354787877866"),
            "status" : 3,
            "user_id" : 4,
        
        }
        ]

Here you can see document which status is 2 and user_id is not equal to 2 is not in expected output but for document which status is other than 2 will come is result


Solution

  • You could use the $or operator: https://mongoplayground.net/p/y9vR2PEGYdI

    db.collection.find({
      $or: [
        {
          status: 2,
          user_id: 2
        },
        {
          status: {
            $ne: 2
          }
        }
      ]
    })