Home > OS >  MongoDB: How to find documents by value?
MongoDB: How to find documents by value?

Time:09-28

Two documents containing ObjectId("6148a371c13a6a0be492ebf4")

Document 1

  {
                "_id" : ObjectId("6144f66fb9543917f96fc"),
                "refId" : "ford",
                "template" : "6144f61cb96d772317f96f9",
                "fieldValues" : {
                    "PDV" : [ 
                        "6126938cd24a8aa3d37b4992", 
                        ObjectId("6148a371c13a6a0be492ebf4")
                ]
            },
            "group" : ObjectId("6144f66fb96d7731917f96fd"),
            "createdAt" : ISODate("2021-09-17T20:11:27.440Z"),
            "updatedAt" : ISODate("2021-09-20T15:06:26.146Z"),
            "__v" : 0
        }

Document 2

 {
            "_id" : ObjectId("6144f66fb96d77rr3217f96fc"),
            "refId" : "CCM",
            "template" : "6144f613296d7731917f96f9",
            "fieldValues" : {
                "DDB" : [ 
                    "6126938cd2448aa3d37b4992", 
                    "5443938cd2448aa3d37b4992", 
                    ObjectId("6148a371c13a6a0be492ebf4"),
                ]
            },
            "group" : ObjectId("6144f66fb96de431917f96fd"),
            "createdAt" : ISODate("2021-09-17T20:11:27.440Z"),
            "updatedAt" : ISODate("2021-09-20T15:06:26.146Z"),
            "__v" : 0
        }

This is one of the examples how I tried to implement this search:

db.getCollection('products').find({$where: function() {
    for (var key in this) {
        if (this[key] === ObjectId("6148a371c13a6a0be492ebf4")) {
            return true;
        }
    }
    return false;
}})

It doesn't work, so maybe you can help me to find solution, Thanks in advance!

CodePudding user response:

db.products.find({'_id': ObjectId("6148a371c13a6a0be492ebf4")})

The mistake in your code is that you used key instead of _id.

This way of writing it is much easier on the fingers though.

CodePudding user response:

You'd think a solution like this would work but one reason why this may not is because you're trying to use === on an object. If you refer to this thread, it might help if you use .equals() instead of ===.

  • Related