0

I have my data in mongo database, and my collection has two fields namely created_at, text, I want to extract a documents having the words like bank, chile and fin in the text field and having created_at value as jan 15.. I am new to mongodb and when I tried to use the below query it gives the error as "unexpected token"

query:

db.tweet.find({$and : [{"created_at" : /.*jan 15.*/i}, {"text : /.*bank.*/i, /.*chile.*/i, /.*fin.*/i "}]})

Please suggest me corrections.Thanks in advance

1 Answer 1

1

This is written wrong. Partly in a redundant use of $and where it is not needed, and secondly I think you mean $or for the second condition. Which actually translates to using the regex form in the easiest sense:

db.tweet.find({
    "created_at": /.*jan 15.*/i,
    "text": /bank|chile|fin/i
})

Actually, use "word boundaries" for more exact "word" matching:

db.tweet.find({
    "created_at": /.*jan 15.*/i,
    "text": /\bbank\b|\bchile\b|\bfin\b/i
})

If you do in fact mean "and" which means the "text" field must contain "all" of those strings, then you need an $and operator. But different to how you did it:

db.tweet.find({
    "created_at": /.*jan 15.*/i,
    "$and": [
        { "text": /.*bank.*/i },
        { "text": /.*chile.*/i },
        { "text": /.*fin.*/i }
    ]
}

The purpose of $and is to allow an "array" construct where the "same" field name is referenced for different conditions. This is so the structure is valid and "key names" are not duplicated.

Otherwise all MongoDB arguments are implicitly an "and" argument always.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your suggestion, I want an and operator in the text field, but when I use your third (last) query, it doesnot gives me anything except "..."
You would need a text field like this in order for that to match: "There is a bank in chile which is hosted by a fin native". Unless that is what you want the last form is not what you want and you mean "or".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.