Обновление:
Я нашел другой способ (может быть простой) сделать это, он должен работать с версией> = 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-Playground
Старый:
В версии 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- Детская площадка