jquerymongodbmongodb-queryobjectidredash

Using Match exp with objectId in MongoDB


I am creating a query with a variable to add a key and corresponding to the key I need to check if the mentioned id is equal to owner id. I used this code with names and it works fine but for Object Id, I am facing errors. I tried toObjectId function but it is not recognisable in MongoDB. How can I use the match function in this case? Where I should add "$oid" function or anything else that can help?

 {"collection": "Sample",
              "aggregate": [
            {"$addFields" : {"Key" : {{ Key }} }},
            {"$project": {"owner": "$owner",
            "check": {"$switch": {"branches": [{"case": {"$eq": ["$Key",556312]},"then": "5efaefc277fabb0d0f7039ab"},
                                {"case": {"$eq": ["$Key",844012]},"then": "5e046b55d1fe060d020f51ac"}
                                ]}}}},
            {"$oid": "check"},
            {"$match" :{"$expr" : {"$eq" :["$owner", "$check"]}}}
    
    ]}

Solution

  • Import Object Id from your driver

    ObjectId = require('mongodb').ObjectID;
    

    And the use it like this since your ids are hard coded:

    ObjectId("5efaefc277fabb0d0f7039ab")