Assume I have a Mongo collection as such:
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.
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.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.