问题
I have a MongoDB collection called references
that has a document where I need to return all the objects that have a key called format
with the value of 1
. An example of the document looks like this:
{
"_id" : ObjectId("878f92ad6d9e8089aa3456a9"),
"categories" : {
"1" : {
"format" : 1,
...
}
}
}
I have tried this:
db.references.find({
"_id" : ObjectId("878f92ad6d9e8089aa3456a9"),
"categories.$.format" : 1
}).pretty();
As well as this:
db.references.find({
"_id" : ObjectId("878f92ad6d9e8089aa3456a9"),
"categories.*.format" : 1
}).pretty();
and both of those are returning nothing.
回答1:
I think schema design is not quite well. Having a schema design like the following:
{
"_id" : ObjectId("57fbe76f78c1638eaebfb21f"),
"categories" : [
{
"cat_name" : 1,
"format" : 1
},
{
"cat_name" : 2,
"format" : 6
}
]
}
Makes much more sense, this way you can access the format
field of the embedded category documents simply using dot notation. The query you requested can be: db.stackQuestion.find({ "categories.format": 1 })
回答2:
The mongoDB enables checking the existance of a field in the document by using the $exists element query operator.
The using of the property _id means that you want to extract specific document from the collection when you know its id so it can return at most 1 object. That is why you should not use the following line inside the query:
"_id" : ObjectId("878f92ad6d9e8089aa3456a9")
Simple query to get all the documents contains the categories field should look like this:
db.references.findAll( {
categories: { $exists: true }
}).pretty();
By using the following query you get in one query all the results you wish to get:
db.references.find({ categories: { $exists:true },
"categories.$" : { $elemMatch: { "format": "1" } }
}).pretty();
The $ is used for deep search for any element under categories.
For more information please read : $match , element match,
来源:https://stackoverflow.com/questions/39964798/query-mongodb-by-value-when-parent-key-is-unknown