仅查询子文档并返回匹配的子文档

编程入门 行业动态 更新时间:2024-10-26 12:23:14
本文介绍了仅查询子文档并返回匹配的子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

仅查询子文档并返回匹配的子文档

本文发布于:2023-11-22 20:17:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618860.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!