I have a collection with records that look like this
{
"_id":{
"$oid":"4e3923963b123b59b73bde67"
},
"ident":"terrainHome",
"columns":[
[
"4e3fbe57dccd1a0cc47509ab",
"4e3fbe57dccd1a0cc47509ac"
],
[
]
]
}
each document can have two or three columns, each column is an array of b开发者_如何学JAVAlocks, which are stored in a different collection, I want a query that will return the ident for the document that contains a block.
I tried
db.things.find({ columns[0] : "4e3fbe57dccd1a0cc47509ac" });
but this didn't work
I'll keep trying. :)
You are mixing types here (ObjectId != String). You should always keep things as ObjectId not sometimes as strings, as you have in the array. This is probably not the root of your problem, but could be problematic later.
In you example you can do this:
db.things.find({ "columns.0" : "4e3fbe57dccd1a0cc47509ac" });
Generally arrays of arrays can be challenging to query on when they are more structured (like embedded docs).
If you don't care about WHERE the match is, try
db.things.find({'columns' : $in : ["4e3fbe57dccd1a0cc47509ac"] });
This works
db.things.find({"$where":"typeof(this.columns[0]) != \"undefined\" && this.columns[0].indexOf(\"4e48ed8245333bd40d000010\") != -1"});
I'll accept my own answer in a couple of days or so, unless someone can suggest a simpler solution.
Also here's a screen grab of the mongo console of the two suggested solutions that didn't work, (thanks though for taking the time), plus the complicated solution I've found that works. The screen grab demos that there are documents in the collection, the two suggested find commands, and the $where javascript solution showing that this works for first item in the array, second item in the array and returns no records for a non matching id.
I've tried dozens of variations of the suggested solutions, but they all turn up blank results.
精彩评论