-->

Trouble updating a specific subdocument with Mongo

2019-07-23 08:03发布

问题:

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 
  }}}