Chapter 4 Advanced CRUD Operations Lab 2

db.companies.find(
{“$and”: [{“stoned_year”: 2004},
		{“$or”: [{“category_code”:”social”},{“category_code”:”web”},{“stoned_month”:”October”}]},
		{“$or”: [{“category_code”:”social”}, {“category_code”:”web”}]}
		]
}) .count()

Spent most of the day trying to figure out why I’m getting an error that the first { is an illegal character? To some of you out there I’m sure it’s obvious? Please help :slight_smile:

First, your quotes are all wrong. Most likely a cut-n-paste from html not formatted correctly.

Then I reformatted and indented your query to:

{
    “$and”:
    [
        { “stoned_year”: 2004 },
        { “$or”:
            [
                {“category_code”:”social”},
                {“category_code”:”web”},
                {“stoned_month”:”October”}
            ]
        },
        { “$or”:
            [
                {“category_code”:”social”},
                {“category_code”:”web”}
            ]
        }
    ]
}

And I see nothing wrong with braces and brackets. May the only issue is the quotes.

But a few things.

  • I do not think that the field is named stoned_year unless they changed it since I took the course.

  • I think your logic is wrong for the year part.

  • Verify the value for stoned_month.

  • For {“$or”: [{“category_code”:”social”}, {“category_code”:”web”}]} take a look at https://docs.mongodb.com/manual/reference/operator/query/in/

  • Using variables makes complex query easier to read. For example, I would write your query as:

year = { "stoned_year" : 2004 }
month = { "stoned_month" : "October" }
social = { "category_code" : "social" }
web = { "category_code" : "web" }
query = { "$and" : 
  [ year ,
    { "$or" : [ social , web , month ] } ,
    { "$or" : [ social , web ] }
  ]
}