Home > Blockchain >  Complex MongoDB query?
Complex MongoDB query?

Time:09-26

I'm pretty brand new to Mongo and queries still, so that said, I'm trying to build a query that will find me results that match these three types of dog breeds and in addition to that, check for additional two specs. And finally, sort all by age. All the data comes from a csv file (scrnshot), there aren't any sub categories to any of the entries.

    db.animals.find({
                     "animal_id" : 1, 
                     "breed" : "Labrador Retriever Mix", 
                     "breed" : "Chesapeake Bay Retriever", 
                     "breed" : "Newfoundland", 
                     $and : [ {  "age_upon_outcome_in_weeks" :{"$lt" : 156, "$gte" : 26} ], 
                     $and: {"sex_upon_outcome" : "Intact Female"}}).sort({"age_upon_outcome_in_weeks" : 1})

This is throwing a number of errors, such as :

Error: error: {
        "ok" : 0,
        "errmsg" : "$and must be an array",
        "code" : 2,
        "codeName" : "BadValue"
}

What am I messing up? Or is there a better way to do it?

CodePudding user response:

As mentionend by takis in the comments, you cannot repeat a key in a mongo query - you have to imagine that your query document becomes a json object, and each time a key is repeated is replaces the previous one. To go around this problem, mongodb supports $or and $and operators. For complex queries like this one, I would recommend starting with a global each containing a single constraint or a $or constraint. Your query becomes this:

db.coll.find({
  "$and": [
    { "animal_id": 1 },
    { "age_upon_outcome_in_weeks": { "$lt": 156, "$gte": 26 } },
    { "sex_upon_outcome": "Intact Female" },
    { "$or": [
      { "breed": "Labrador Retriever Mix" },
      { "breed": "Chesapeake Bay Retriever" },
      { "breed": "Chesapeake Bay Retriever" },
      { "breed": "Newfoundland" }
      ]
    }
  ]
})
.sort({"age_upon_outcome_in_weeks" : 1})

--- edit

You can also consider using the $in instead of the $or:

db.coll.find({
    "animal_id": 1,
    "age_upon_outcome_in_weeks": { "$lt": 156, "$gte": 26 },
    "sex_upon_outcome": "Intact Female",
    "breed": { "$in": [ 
        "Labrador Retriever Mix",
        "Chesapeake Bay Retriever",
        "Chesapeake Bay Retriever",
        "Newfoundland" 
    ] }
  })
  .sort({"age_upon_outcome_in_weeks" : 1})
  • Related