mongodb - MongoDB - 如何用长度查询没有任何空格的字符串(省略带空格的字符串)
问题描述
我已将长度匹配的文档查询为:
文件样本格式:
{
"_id": {
"$oid": "5e158e2de6facf7181cc368f"
},
"word": "as luck would have it",
}
查询为:
{$where: "this.word.length == 20 "}
这符合以下内容:
{
"_id": {
"$oid": "5e158e30e6facf7181cc3bdb"
},
"word": "adrenocorticotrophic",
}
{
"_id": {
"$oid": "5e158e2ee6facf7181cc38cf"
},
"word": "attributive genitive",
}
但我只想不匹配adrenocorticotrophic
带有空格的单词attributive genitive
我可以知道我怎么能像上面那样匹配?
任何帮助表示赞赏!
解决方案
更新 :
我找到了另一种方法(可能很简单),它应该与 version >= 一起使用3.4
,试试这个:
/** When you split a string on a delimiter(space in your requirement) it would split string into an array of elements,
* if no space in string then it would be only one element in array, then get a size & get docs having size less than 2 */
db.collection.aggregate([
{
$match: {
$expr: {
$lt: [
{
$size: {
$split: [
"$word", // word should not be null or '' (can be empty ' ')
" "
]
}
},
2
]
}
}
}
])
测试: MongoDB-游乐场
老的 :
在 MongoDB 版本 >=4.2
上,您可以使用$regexMatch做到这一点:
db.collection.aggregate([
/** A new field gets added to be true if word has spaces else be false */
{
$addFields: {
wordHasSpaces: {
$regexMatch: {
input: "$word",
regex: /\w+\s\w+/ /** This regex exp works if your string has plain characters A-Z */
}
}
}
},
/** Remove docs where word has spaces */
{ $match: { wordHasSpaces: false } },
/** Remove newly added unnecessary field */
{ $project: { wordHasSpaces: 0 } }
]);
同样对于您现有的代码,您可以停止使用$where
通常用于在查询中执行 .js 代码的性能较低的代码,因此在 MongoDB v >= 上,3.4
您可以使用$strLenCP:
db.collection.aggregate([{$match : {$expr: {$eq : [{ $strLenCP:'$word'}, 20]}}}]) /** $expr is kind of replacement to $where */
测试: MongoDB-游乐场
推荐阅读
- android - 列表与详细视图重叠
- unity3d - 我可以在没有项目设置的情况下在 c# 代码中#define 一个常量解决方案范围吗?
- ios - 如何在我的网站中关闭自动睡眠 ios
- c# - SignalR 从客户端发送数据
- android - 如何从签名的消息中恢复地址?
- kubernetes - Kubernetes 的服务仍处于待处理状态。它是如何工作的以及如何解决这个问题?
- javascript - React.js 拼接从数组列表中删除错误的项目
- python - 当我尝试在 django 中进行迁移时,出现未定义的 DJANGO_SETTINGS_MODULE 错误
- android - 从 Glide 获取链接以稍后将其用作资源
- javascript - 如何将带有子查询的 SQL 查询解析到字段中?