如果你想只得到了整個文檔的一部分,使用所謂的Projection operators
請參見下面的例子:
> db.collection.find().pretty()
{
"_id" : ObjectId("52e861617acb7ce761e64a93"),
"entity_id" : 2,
"features" : [
{
"10" : "name"
},
{
"20" : "description"
},
{
"90" : "availability"
}
]
}
投影運營商都在尋找(指定)喜歡這裏:
> db.collection.find({},{ features : { $elemMatch : { 20 : { $exists: true } }}}).pretty()
{
"_id" : ObjectId("52e861617acb7ce761e64a93"),
"features" : [
{
"20" : "description"
}
]
}
> db.collection.find({},{ entity_id : 1, features : { $elemMatch : { 20 : { $exists: true } }}}).pretty()
{
"_id" : ObjectId("52e861617acb7ce761e64a93"),
"entity_id" : 2,
"features" : [
{
"20" : "description"
}
]
}
> db.collection.find({},{ _id : 0, entity_id : 1, features : { $elemMatch : { 20 : { $exists: true } }}}).pretty()
{ "entity_id" : 2, "features" : [ { "20" : "description" } ] }
$elemMatch
for projection在自2.2版以來的MongoDB中可用。
希望它能解決您的問題。
.find({'features.20':{$ exists:true}}) – portforwardpodcast
這將給出整個文檔。我只想要屬性是20的元素文件 – Alex
http://stackoverflow.com/questions/9289384/select-only-subdocuments-or-arrays – portforwardpodcast