0

I am new to MongoDB and am learning how to query for multiple things at once with conditionals. I have a database with a document called 'towns' that contains an id, name, population, date of last census, items it is famous for, and mayor. For example, this is what one of the towns looks like (please keep in mind, this is old, random data, nothing is up to date, it is just an example for me to learn):

{
        "_id" : ObjectId("60232b0bbae1e5336c5ebc96"),
        "name" : "New York",
        "population" : 22200000,
        "lastCensus" : ISODate("2016-07-05T00:00:00Z"),
        "famousFor" : [
                "the MOMA",
                "food"

        ],
        "mayor" : {
                "name" : "Bill de Blasio",
                "party" : "D"
        }

I am trying to find all towns with names that contain an e and that are famous for food or beer. I currently have this query:

db.towns.find({name: {$regex:"e"}}, {$or: [{famousFor:{$regex: 'food'}}, {famousFor:{$regex: 'beer'}}]})

If I split up the name and the $or expression, it works, but together I get errors like:

Error: error: {
        "ok" : 0,
        "errmsg" : "Unrecognized expression '$regex'",
        "code" : 168,
        "codeName" : "InvalidPipelineOperator"

Or, if I switch the query to db.towns.find({name:/e/}, {$or: [{famousFor:/food/}, {famousFor:/beer/}]}) I get the error:

Error: error: {
        "ok" : 0,
        "errmsg" : "FieldPath field names may not start with '$'.",
        "code" : 16410,
        "codeName" : "Location16410"

What am I doing wrong? Is it how I am structuring the query?

Thanks in advance!

1 Answer 1

1

Problem Is the syntax.

find({condition goes here}, {projection goes here})

You need to put all of your conditions within one curly brace.

db.towns.find({name: {$regex:"e"}, $or: [{famousFor:{$regex: 'food'}}, {famousFor:{$regex: 'beer'}}]})
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh! Thank you so much!

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.