c 示例 Mongo 文档
cExample Mongo Document
{ "_id": ObjectId("5652e77f21b0f1f2692558a1"), "category": "clothing", "Brand": [ { "name": "Adidas", "key": "Adidas" }, { "name": "Reebok", "key": "Reebok" }, { "name": "Puma", "key": "Puma" } ], "Color": [ { "name": "Red", "key": "Red" }, { "name": "Green", "key": "Green" }, { "name": "Blue", "key": "Blue" } ] }现在我想搜索名称为 Adidas 或 Puma 的品牌.其他要求是只返回子文档,所以我尝试了下面给出的查询
Now I want to search for Brands where name is either Adidas or Puma. Other requerement is to return sub document only so I tried query given below
find( { "Brand.name" : { $in : ["Reebok", "Adidas"]}},{"Brand" : 1,"_id" : 0})
find( { "Brand.name" : { $in : ["Reebok", "Adidas"]}},{"Brand" : 1, "_id" : 0})
但它返回了我品牌数组的所有三个对象
But its returning me all three objects of Brand array
{ "Brand" : [ { "name" : "Adidas", "key" : "Adidas" }, { "name" : "Reebok", "key" : "Reebok" }, { "name" : "Puma", "key" : "Puma" } ] }我当然也可以通过 Javascript 来完成(通过重新调整的数组和匹配值进行迭代),但是有什么方法可以仅使用 Mongo Query 来解决我的目的.
I can sertainly do it through Javascript as well (Iterating through retuned array and metching values) but Is there any way to get my purpose solved with Mongo Query only.
注意:在支持 JSON 文档的 NoSql 系统中,最大的区别是这些系统不支持关系,但您始终可以通过子文档维护关系.如果这样的查询(上面提到的)是不可能的,那么我认为以子文档形式保存数据不是一个好习惯,因为你不能随意查询它.专家对此有何看法????
Note : In NoSql Systems, where JSON documents are supported, biggest difference is these systems doesn't support relationships but you can always maintain relations by subdocuments. If such queries (mentioned above) are not possible then I think holding data in subdocument form is not good practise as you can not query it as you want. Expert Thoughts on this????
推荐答案$in in find 查询旨在返回文档而不是子文档.在您的情况下,mongoDB 提供了聚合框架.这将帮助您过滤子文档.
$in in find query is designed to return documents rather than sub documents. In your case mongoDB has provided the aggregation framework. This will help you filter sub documents.
对于 mongoDB <= 3.0.x
db.collection.aggregate( { $project: { Brand: 1}}, { $unwind: '$Brand'}, { $match: { "Brand.name" : { $in : ["Reebok", "Adidas"]}}}, { $group: { _id: '$_id', Brand: {$push : '$Brand' }}} )MongoDB 3.2 方式
db.collection.aggregate([ { $project: { Brand: { $filter: { input: "$Brand", as: "Brand", cond: { "$$Brand.name": { $in : ["Reebok", "Adidas"]}} } } } } ])更多推荐
仅查询子文档并返回匹配的子文档
发布评论