如何按ObjectId的部分查找文档? [英] How to find document by parts of ObjectId?

查看:92
本文介绍了如何按ObjectId的部分查找文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我使用 MongoDB 本机 ObjectId 作为我的应用程序票证识别号的主键.是否可以搜索带有 ObjectId 部分的文档?

例如:我有文件:

<预><代码>[{_id: ObjectId("577f8e6537e4a676203c056a")},{_id: ObjectId("577f8ee437e4a676203c0577")},{_id: ObjectId("577f8f3d717b6fdd22a1684c")}]

我想通过它的 _id 包含0577"来查询它,以便它返回

 {_id: ObjectId("577f8ee437e4a676203c0577")}

我以前尝试过正则表达式.它返回了 []

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

解决方案

我认为你可以使用 $where 像这样:

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

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

解决方案

I think you can use $where like this:

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

这篇关于如何按ObjectId的部分查找文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆