mongodbobjectid

How to find document by parts of ObjectId?


For some reason I use MongoDB native ObjectId as primary key for ticket identification number for my application. Is it possible to search documents with ObjectId parts?

For example: I have documents:

[
    {_id: ObjectId("577f8e6537e4a676203c056a")},
    {_id: ObjectId("577f8ee437e4a676203c0577")},
    {_id: ObjectId("577f8f3d717b6fdd22a1684c")}
]

And I want to query it by its _id contains "0577" so that it returns

 {_id: ObjectId("577f8ee437e4a676203c0577")}

I have tried regex before. It returned []

db.transaction.find({_id: /0577/i}) ---> return 0
db.transaction.find({_id: {$regex: /0577/, $options: "i"}}) ---> return 0

Solution

  • I think you can use $where like this:

    db.transaction.find({ $where: "this._id.str.match(/.*0577/)" })