简体   繁体   English

查找和更新部分嵌套集合

[英]Find & Update partial nested collection

Assume I have a Mongo collection as such: 假设我有一个Mongo集合,例如:

The general schema: There are Categories, each Category has an array of Topics, and each Topic has a Rating. 通用模式:有类别,每个类别都有一个主题数组,每个主题都有一个评级。

[
{CategoryName: "Cat1", ..., Topics: [{TopicName: "T1", rating: 9999, ...}, 
{TopicName: "T2", rating: 42, ....}]},
{CategoryName: "Cat2", ... , Topics: [...]},
...
]

In my client-side meteor code, I have two operations I'd like to execute smoothly, without any added filtering to be done: Finding, and updating. 在我的客户端流星代码中,我有两个要平滑执行的操作,而无需执行任何其他过滤操作:查找和更新。

I'm imagining the find query as follows: 我想象如下的查找查询:

.find({CategoryName: "Cat1", Topics: [{TopicName: "T1"}]}).fetch()

This will, however, return the whole document - The result I want is only partial: 但是,这将返回整个文档-我想要的结果只是部分的:

[{CategoryName: "Cat1", ..., Topics: [{TopicName: "T1", rating: 9999, ...}]}]

Similarly, with updating, I'd like a query somewhat as such: 同样,通过更新,我希望查询如下:

.update({CategoryName: "Cat1", Topics: [{TopicName: "T1"}]}, {$set: {Topics: [{rating: infinityyy}]}})

To only update the rating of the topic T1, and not all topics of category Cat1. 仅更新主题T1的等级,而不是类别Cat1的所有主题的等级。

Again, I'd like to avoid any filtering, as the rest of the data should not even be sent to the client in the first place. 同样,我想避免任何过滤,因为其余的数据甚至不应该首先发送到客户端。

Thanks! 谢谢!

You need to amend your query to the following: 您需要将查询修改为以下内容:

Categories.find( { CategoryName: 'Cat1', 'Topics.TopicName': 'T1' }, { fields: { 'Topics.$': 1 }}, // make sure you put any other fields you want in here too ).fetch()

What this query does is searches for a Category that matches the name Cat1 and has the object with the TopicName equal to T1 inside the Topic array. 该查询的作用是搜索与名称Cat1匹配的Category,并且在Topic数组中具有TopicName等于T1的对象。

In the fields projection we are using the $ symbol to tell MongoDB to return the object that was found as part of the query, and not all the objects in the Topics array. fields投影中,我们使用$符号告诉MongoDB返回在查询中找到的对象,而不是Topics数组中的所有对象。

To update this nested object you need to use the same $ symbol: 要更新此嵌套对象,您需要使用相同的$符号:

Categories.update( { CategoryName: "Cat1", 'Topics.TopicName': 'T1' }, {$set: {'Topics.$.rating': 100 }, );

Hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM