0

I have documents that look like this:

{
  "_id":"5883d55ee4b05d652e466108",
  "result":"FAILURE",
  "failureCauses":[
    {
      "failureCause":
        {
          "$ref":"failureCauses", 
          "$id":"5883d33de4b05d652e4660d4", 
          "$db":""
        }, 
      "indications": [ 
        { 
          "pattern":"^FATAL: .*$", 
          "matchingFile":"log", 
          "matchingString":"FATAL: all hosts have already failed -- aborting"
        }
      ]
    },
    {
      "failureCause":
        {
          "$ref":"failureCauses",
          "$id":"5883d33de4b05d652e4660e3",
          "$db":""
        },
      "indications":[
        {
          "pattern":".*command not found.*",
          "matchingFile":"log",
          "matchingString":"bash: rsync: command not found"
        }
      ]
    }
  ]
}

How do I get all documents which have a specific failureCauses array member? (I do have the $id.)

Note, I already tried the queries below but it does not return any results:

{"failureCauses" : new ObjectId("myid") }
{"failureCauses" : { "$in" : [ ObjectId("myid") ]}}
Vince Bowdren
  • 8,326
  • 3
  • 31
  • 56
sorin
  • 161,544
  • 178
  • 535
  • 806
  • Lose the `DBRef` from your implementation. It's as close to deprecated as you can get, and certainly not supported in any of the newer features in modern MongoDB releases. Instead go for a plain `ObjectId` and have your application schema identify the "related" collection from the "client side". – Neil Lunn May 03 '18 at 22:45

2 Answers2

2

Single criteria

You can concatenate the name of the array field, with a dot (.) and the name of the field in the nested document:

{
  "failureCauses.failureCause.$id": "5883d33de4b05d652e4660e3"
}

Multiple criteria

If instead you want to query for an Array element that meets multiple criteria, use $elemMatch operator to specify multiple criteria on the elements of an array such that at least one array element satisfies all the specified criteria:

{
  "failureCauses": {
    "$elemMatch": {
      "failureCause.$id": "5883d33de4b05d652e4660e3",
      "failureCause.$ref": "failureCauses"
    }
  }
}
Ezequias Dinella
  • 1,278
  • 9
  • 12
1

Elements in a json Array can be chained using the dot notation . Following query should work

db.exp.find({"failureCauses.failureCause.$id":"5883d33de4b05d652e4660d4"})
mintekhab
  • 203
  • 1
  • 3