问题描述
我的文档如下:
{
_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")
}
]
}
我的查询是:{ txid: '7e621eeb02874ab039a8566fd36f4591e65eca65313875221842c53de6907d6c', 'vin.txid': 'c04c413576307737f3ad48efe5d509ebc883e1d04822b3a2eccf6a80a4482932', 'vin.vout': 0 }
My Query is:{ txid: '7e621eeb02874ab039a8566fd36f4591e65eca65313875221842c53de6907d6c', 'vin.txid': 'c04c413576307737f3ad48efe5d509ebc883e1d04822b3a2eccf6a80a4482932', 'vin.vout': 0 }
更新为:
{ 'vin.$.meta_address': '321',
'vin.$.meta_amount': 50 }
但是,当我运行它时,它将更新vin
数组中的第一项,而不是第二项.现在,奇怪的是,如果我将查询更改为:{ txid: '7e621eeb02874ab039a8566fd36f4591e65eca65313875221842c53de6907d6c', 'vin.txid': 'c04c413576307737f3ad48efe5d509ebc883e1d04822b3a2eccf6a80a4482932'}
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'}
然后正常工作.我认为问题是我的查询在vin
中查找了2个元素,但是我需要按两个元素进行搜索.我在做什么错了?
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?
推荐答案
要在更新中获取$
以标识与查询中的两个属性均匹配的元素,您需要在查询对象中使用$elemMatch
:
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
}}}
这篇关于无法使用MongoDB更新特定的子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!