Trouble updating a specific subdocument with MongoDB

邮差的信 提交于 2019-12-11 13:22:34

问题


My document looks like:

{
  _id: ObjectId("52d317d7b5c4960000587cd4"),
  txid: "7e621eeb02874ab039a8566fd36f4591e65eca65313875221842c53de6907d6c",
  vin: [
    {
      _id: ObjectId("52d317d7b5c4960000587ce9"),
      meta_address: "321",
      meta_amount: 50,
      sequence: 4294967295,
      txid: "6749762ae220c10705556799dcec9bb6a54a7b881eb4b961323a3363b00db518",
      vout: 0
    },
    {
      _id: ObjectId("52d317d7b5c4960000587ce8"),
      sequence: 4294967295,
      txid: "c04c413576307737f3ad48efe5d509ebc883e1d04822b3a2eccf6a80a4482932",
      vout: 0
    },
    {
      txid: "72d4fc43ac576a4b2f1f35e1b310a2d83a1012a36fdc7813ec237646950233cf",
      vout: 0,
      sequence: 4294967295,
      _id: ObjectId("52d317d7b5c4960000587ce7")
    }
  ]
}

My Query is: { txid: '7e621eeb02874ab039a8566fd36f4591e65eca65313875221842c53de6907d6c', 'vin.txid': 'c04c413576307737f3ad48efe5d509ebc883e1d04822b3a2eccf6a80a4482932', 'vin.vout': 0 }

and the update is:

{ 'vin.$.meta_address': '321',
  'vin.$.meta_amount': 50 }

But when I run it, it updates the first item in the vin array instead of the second. Now, oddly enough, if I change the query to: { txid: '7e621eeb02874ab039a8566fd36f4591e65eca65313875221842c53de6907d6c', 'vin.txid': 'c04c413576307737f3ad48efe5d509ebc883e1d04822b3a2eccf6a80a4482932'}

then it works fine. I think the problem is that my query looks for 2 elements in the vin, but I need to search by both. What am I doing wrong?


回答1:


To get the $ in your update to identify the element that matches both properties in your query, you need to use $elemMatch in your query object:

{ txid: '7e621eeb02874ab039a8566fd36f4591e65eca65313875221842c53de6907d6c', 
  vin: {$elemMatch: {
      txid: 'c04c413576307737f3ad48efe5d509ebc883e1d04822b3a2eccf6a80a4482932', 
      vout: 0 
  }}}


来源:https://stackoverflow.com/questions/21082804/trouble-updating-a-specific-subdocument-with-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!