Query nested objects in a document with unknown key

It will be hard to achieve something with the schema. I would consider using Building with Patterns: The Attribute Pattern | MongoDB Blog.

{
    "_id" : ObjectId("60054d3e20b5c978eb93bb7f"),
	"items": [
		{       "k" : "o1n2rpon12prn" ,
			"LastEvent": "On"
		},
		{    "k" : "sdbqw12f12f" ,
		    "LastEvent": "Off"
		},
		{     "k" : "yxvcaqeg23g23g",
		     "LastEvent": "Error"
		}
	]
}

You can then have a multi-keys index on items.k and with $elemMatch (or $unwind and $match) you can find the k for which LastEvent:On.

Just the names o1n2rpon12prn, sdbqw12f12f and yxvcaqeg23g23g gives me the feeling that they should be values rather than keys.

1 Like