MongoDB - 如何仅选择数字字符串/在 mongo-shell 中检查字符串是否为数字 [英] MongoDB - How to select only numeric strings / Check whether string is numeric in mongo-shell
问题描述
我有一个集合,其中的字段是字符串,但这些字符串可以在其中包含一个数值,例如:
I have a collection where the fields are string but those strings can have a numeric value inside e.g.:
我的对象:{
示例:[
{example: "words", ...},
{example: "more words", ...},
{example: "111", ...},
{example: "4502", ...}
...
]
...
}
myObject: {
examples: [
{example: "words", ...},
{example: "more words", ...},
{example: "111", ...},
{example: "4502", ...}
...
]
...
}
如何以字符串格式查询111"和4502"以及任何其他数值?
How can I query "111" and "4502" and any other numeric values in string format?
推荐答案
您可以在查询对象中使用正则表达式来做到这一点:
You can use a regular expression in your query object to do that:
// Select docs where at least one examples element contains an example value
// that's made up only of digits.
db.test.find({'examples.example': /^\d+$/})
这篇关于MongoDB - 如何仅选择数字字符串/在 mongo-shell 中检查字符串是否为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!