我有一个收藏品
users
{
"_id" : ObjectId("53738eb7ac8ee07007c1d75a"),
"first" : "Shivam",
"connections" : [
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-16T00:00:00Z"),
"fl" : "LB",
"TYP" : "ZLP",
"invit_reciv" : [ ],
},
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-20T00:00:00Z"),
"fl" : "LB",
"invit_reciv" : [ ],
"TYP" : "ZLP",
}
]
}
我正在执行连接中的日期更新,但在我的情况下会更新错误的嵌套文档。
db.users.update(
{ 'connections.TYP' : 'ZLP'
,'connections.fl' : 'LB'
,'connections.date' : ISODate("2014-05-20T00:00:00Z")
},
{ '$addToSet' : {
'connections.$.invit_reciv' : { 'last' : 'abc'}
}
})
实际结果我收到了。
{
"_id" : ObjectId("53738eb7ac8ee07007c1d75a"),
"first" : "Shivam",
"connections" : [
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-16T00:00:00Z"),
"fl" : "LB",
"TYP" : "ZLP",
"invit_reciv" : [
{
"last" : "abc"
}
],
},
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-20T00:00:00Z"),
"fl" : "LB",
"invit_reciv" : [ ],
"TYP" : "ZLP",
}
]
}
我期待的结果
{
"_id" : ObjectId("53738eb7ac8ee07007c1d75a"),
"first" : "Shivam",
"connections" : [
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-16T00:00:00Z"),
"fl" : "LB",
"TYP" : "ZLP",
"invit_reciv" : [ ],
},
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-20T00:00:00Z"),
"fl" : "LB",
"invit_reciv" : [
{
"last" : "abc"
}
],
"TYP" : "ZLP",
}
]
}
请帮助我了解当前查询中发生了什么以及它有什么问题。
答案 0 :(得分:1)
你应该使用$ elemMatch和位置运算符,它允许你匹配特定的嵌套doc:
db.users.update(
{ connections:{
$elemMatch:{
'TYP' : 'ZLP',
'fl' : 'LB',
'date' : ISODate("2014-05-20T00:00:00Z")
}
}
},
{ '$addToSet' : {
'connections.$.invit_reciv' :
{ 'last' : 'abc'}
}
}
)