14
仅检索MongoDB集合中对象数组中的查询元素
假设您的收藏夹中包含以下文档: { "_id":ObjectId("562e7c594c12942f08fe4192"), "shapes":[ { "shape":"square", "color":"blue" }, { "shape":"circle", "color":"red" } ] }, { "_id":ObjectId("562e7c594c12942f08fe4193"), "shapes":[ { "shape":"square", "color":"black" }, { "shape":"circle", "color":"green" } ] } 进行查询: db.test.find({"shapes.color": "red"}, {"shapes.color": 1}) 要么 db.test.find({shapes: {"$elemMatch": {color: "red"}}}, {"shapes.color": 1}) 返回匹配的文档(文档1),但始终包含以下所有数组项shapes: { "shapes": [ {"shape": "square", "color": "blue"}, {"shape": "circle", "color": …