How to find document by parts of ObjectId?

狂风中的少年 提交于 2021-01-27 18:09:50

问题


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

回答1:


I think you can use $where like this:

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


来源:https://stackoverflow.com/questions/38277495/how-to-find-document-by-parts-of-objectid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!