Reputation: 21
It's been a while since I've worked with mongo and I feel I'm losing it with this one.
I have a series of documents in a collection in the form of:
{
_id,
title: string,
description: string,
location: string
...
}
and I want to search those documents by two queries:
1st query - search in title and description, 2nd query - search in location
it should only return results that match both queries.
Or SQL equivalent:
SELECT *
FROM `docs`
WHERE (`title` LIKE '%query_ONE%' OR `description` LIKE '%query_ONE%')
AND `city` LIKE '%query_TWO%'
I have pretty much searched and tried every solution here and so far it seems to be a problem with "location" field as it always returns nothing on search/find, while on title / description it works fine. I think my index is bad or something. I admit I'm not too familiar with indexing / more advanced searching, so I'm hoping for some guidance on this one.
Thanks.
Upvotes: 0
Views: 64
Reputation: 17915
You need to try $or :
db.docs.find({$or:[{title:'title'}, {description:'des'}], location:'my'})
Collection :
/* 1 */
{
"_id" : ObjectId("5dfeac7b400289966e2042c7"),
"title" : "title",
"description" : "des",
"location" : "my"
}
/* 2 */
{
"_id" : ObjectId("5dfeac84400289966e204380"),
"title" : "title1",
"description" : "des1",
"location" : "my"
}
/* 3 */
{
"_id" : ObjectId("5dfeac8b400289966e2043ec"),
"title" : "title",
"description" : "des",
"location" : "my1"
}
/* 4 */
{
"_id" : ObjectId("5dfead06400289966e204e1e"),
"title" : "title1",
"description" : "des1",
"location" : "my1"
}
/* 5 */
{
"_id" : ObjectId("5dfeae24400289966e2067ad"),
"title" : "title",
"description" : "des1",
"location" : "my"
}
/* 6 */
{
"_id" : ObjectId("5dfeae2f400289966e206894"),
"title" : "title1",
"description" : "des",
"location" : "my"
}
Result :
/* 1 */
{
"_id" : ObjectId("5dfeac7b400289966e2042c7"),
"title" : "title",
"description" : "des",
"location" : "my"
}
/* 2 */
{
"_id" : ObjectId("5dfeae24400289966e2067ad"),
"title" : "title",
"description" : "des1",
"location" : "my"
}
/* 3 */
{
"_id" : ObjectId("5dfeae2f400289966e206894"),
"title" : "title1",
"description" : "des",
"location" : "my"
}
Upvotes: 1
Reputation: 558
You can combine the two conditions using an aggregation pipeline. See https://docs.mongodb.com/manual/core/aggregation-pipeline/ and https://api.mongodb.com/python/current/examples/aggregation.html
Upvotes: 0