问题
sample format of document:
{
"_id": {
"$oid": "5e158e2de6facf7181cc368f"
},
"word": "as luck would have it",
}
I am trying to match multiple conditions in an expression as:
query = {
"$match": {
"$expr": {"$eq": [{"$strLenCP": "$word"}, 6],
'$lt': [
{
'$size': {
'$split': [
"$word",
" "
]
}
},
2
]
}
}
}
And pipe line as follows:
pipeline = [query]
cursor_objects = db['test'].aggregate(pipeline)
In the above query I am trying to achieve word length must be 6 and it doesn't contain any spaces
When I did this I am getting and error :
pymongo.errors.OperationFailure: An object representing an expression must have exactly one field: { $eq: [ { $strLenCP: "$word" }, 6 ], $lt: [ { $size: { $split: [ "$word", " " ]
May I know how could I achieve this ?
any help is appreciated ,...TIA
回答1:
To use multiple conditions in $expr you have to use $and operator
query = {
$match: {
$expr: {
$and: [
{
$lt: [
{
$size: {
$split: ["$word", " "]
}
},
2
]
},
{ $eq: [{ $strLenCP: "$word" }, 6] }
]
}
}
};
回答2:
Try this:
query = {
"$match": {
"$expr": {
$and: [{
"$eq": [{ "$strLenCP": "$word" }, 6]
}, {
'$lt': [{
'$size': {
'$split': [
"$word",
" "
]
}
},
2
]
}]
}
}
}
来源:https://stackoverflow.com/questions/60721090/match-multiple-conditions-in-an-aggregate-under-expressions