仅查询子文档并返回匹配的子文档 [英] Querying Subdocument and Returning Matching Subdocument only

查看:61
本文介绍了仅查询子文档并返回匹配的子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"]}}
            }
         }
      }
   }
])

这篇关于仅查询子文档并返回匹配的子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆