更新数组中的元素 [英] Update Elements in Array

查看:66
本文介绍了更新数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有这个对象:

Lets say I have this Object:

{town_id: 13, houses_data: [
    {house_id: 5, price: 32, description: "thats a house"},
    {house_id: 2, price: 12, description: "thats a house"}
   ]
 }

我想将ID为5的房屋的描述更新为出售":

{town_id: 13, houses_data: [
    {house_id: 5, price: 32, description: "sold"},
    {house_id: 2, price: 12, description: "thats a house"}
   ]
 }

我尝试过的事情:

 town1 = town.findOne({town_id: 13});

获取房屋数据:

 twon1.houses_data

并尝试仅更新house_data,其中id = 5

 twon1.houses_data.find({house_id: 5}).update(description: "sold");

但我收到此错误消息:

 [object Object],[object Object] has no method 'find'

我怎么了?谢谢

推荐答案

您可以使用

You might use $ to update the first embedded document matching the given query:

db.test.town.update({town_id: 13, "houses_data.house_id":5},
                    {$set: { "houses_data.$.description": "sold"}})

这篇关于更新数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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