Reputation: 11
I set index for data field below, then trying to get the count of particular text search content and over all text content
My input is like this below:
{
_id: 14572
data: "selling bike in india"
}
{
_id: 14673
data: "sale bike in india"
}
{
_id: 14673
data: "buying cars in india"
}
I tired to get the count of cars, bike and total documents from collection, unfortunately not getting it,
db.collection.aggregate([
{
"Total": [
{$match:{"$text":{$search:"india"}}},
{ "$count": "Total" },
],
"bike": [
{$match:{"$text":{$search:"bike"}}},
{ "$count": "bike" }
]
{ "$project": {
"Total": { "$arrayElemAt": ["$Total.Total", 0] },
"bike": { "$arrayElemAt": ["$bikebike.Birds", 0] }
}}
])
expected output like below
Total:3
bike:2
car:1
Upvotes: 0
Views: 153
Reputation: 28366
The $text
operator has some restrictions described at https://docs.mongodb.com/manual/reference/operator/query/text/index.html
A couple relevant to this query:
A query can specify, at most, one $text expression.
If using the $text operator in aggregation, the following restrictions also apply.
The $match stage that includes a $text must be the first stage in the pipeline.
Since you are trying to do separate text searches for different strings, you'll need to do each one separately, like
db.collection.count({$text:{$search:"india"}})
db.collection.count({$text:{$search:"bike"}})
db.collection.count({$text:{$search:"car"}})
Upvotes: 1