如何获取 Mongoose 中字符串字段的长度?
How to get the length of a string field in Mongoose?
我是 MongoDB 和 Mongoose 的新手。
我正在使用以下架构和模型练习一些查询:
const articleSchema = mongoose.Schema({
title: String,
content: String,
});
const Article = mongoose.model('article', articleSchema);
假设我添加了以下两个文件:
{title: "One", content: "Content One"}
{title: "LongerTitleThanOne", content: "Content Two"}
我可以使用哪个查询来查找“标题”长度大于 3 的所有文档?
我尝试了以下查询,但它只适用于数字:
Article.find({title:{$gt:3}}, (err,foundItems)=>{});
在此先感谢您的帮助。
Article.find({
"$expr": {
"$gt": [
{
"$strLenCP": "$title"
},
3
]
}
})
也可以使用聚合查询来实现结果。
Article.aggregate(
[
{
'$project': {
'titleLength': { '$strLenCP': '$name' }
}
}, {
'$match': {
'titleLength': {
'$gt': 2
}
}
}
])
这不是最好的方法,但很有效
我建议你不要在生产中使用它。
首先从数据库中获取所有数据并将其存储在变量中,然后使用 JavaScript 过滤功能来完成任务
例如
let data = model.find({});
let filter_data = data.filter(data.title.length>8);
我是 MongoDB 和 Mongoose 的新手。
我正在使用以下架构和模型练习一些查询:
const articleSchema = mongoose.Schema({
title: String,
content: String,
});
const Article = mongoose.model('article', articleSchema);
假设我添加了以下两个文件:
{title: "One", content: "Content One"}
{title: "LongerTitleThanOne", content: "Content Two"}
我可以使用哪个查询来查找“标题”长度大于 3 的所有文档?
我尝试了以下查询,但它只适用于数字:
Article.find({title:{$gt:3}}, (err,foundItems)=>{});
在此先感谢您的帮助。
Article.find({
"$expr": {
"$gt": [
{
"$strLenCP": "$title"
},
3
]
}
})
也可以使用聚合查询来实现结果。
Article.aggregate(
[
{
'$project': {
'titleLength': { '$strLenCP': '$name' }
}
}, {
'$match': {
'titleLength': {
'$gt': 2
}
}
}
])
这不是最好的方法,但很有效
我建议你不要在生产中使用它。
首先从数据库中获取所有数据并将其存储在变量中,然后使用 JavaScript 过滤功能来完成任务
例如
let data = model.find({});
let filter_data = data.filter(data.title.length>8);