我有一个MongoDB嵌入式文档,其中包含许多数组文档。
EX:
{
"_id" : ObjectId("594b7b7d4064e264420e38d0"),
"UnitId" : "594b75d44064e264420e3869",
"UnitName" : "PARKING",
"UnitIcon" : "./upload/file-1498117588607.jpg",
"Stream" : {
"_id" : ObjectId("594b7b7d4064e264420e38d1"),
"Types" : [
{
"TypeId" : "594b9a884064e264420e3b56",
"TypeName" : "TR/RC",
"Travel" : false
},
{
"TypeId" : "594b9a844064e264420e3b55",
"MaterialStreamName" : "RW",
"Travel_Required" : false
},
{
"TypeId" : "594b9a9d4064e264420e3b58",
"TypeName" : "ST",
"Travel_Required" : true
},
{
"TypeId" : "594b9a764064e264420e3b53",
"TypeName" : "FD",
"Travel_Required" : true
}
]
}
},{
"_id" : ObjectId("594b7b7d4064e264420e38d1"),
"UnitId" : "594b75d44064e264420e3870",
"UnitName" : "CAFE",
"UnitIcon" : "./upload/file-1498117588608.jpg",
"Stream" : {
"_id" : ObjectId("594b7b7d4064e264420e38d2"),
"Types" : [
{
"TypeId" : "594b9a884064e264420e3b56",
"TypeName" : "TR/RC",
"Travel" : false
},
{
"TypeId" : "594b9a844064e264420e3b55",
"MaterialStreamName" : "RW",
"Travel_Required" : false
},
{
"TypeId" : "594b9a9d4064e264420e3b58",
"TypeName" : "ST",
"Travel_Required" : true
},
{
"TypeId" : "594b9a764064e264420e3b53",
"TypeName" : "FD",
"Travel_Required" : true
}
]
}
},{
"_id" : ObjectId("594b7b7d4064e264420e38d2"),
"UnitId" : "594b75d44064e264420e3870",
"UnitName" : "CAFE",
"UnitIcon" : "./upload/file-1498117588608.jpg",
"Stream" : {
"_id" : ObjectId("594b7b7d4064e264420e38d3"),
"Types" : [
{
"TypeId" : "594b9a9d4064e264420e3b58",
"TypeName" : "ST",
"Travel_Required" : true
},
{
"TypeId" : "594b9a884064e264420e3b56",
"TypeName" : "TR/RC",
"Travel" : false
},
{
"TypeId" : "594b9a844064e264420e3b55",
"MaterialStreamName" : "RW",
"Travel_Required" : false
},
{
"TypeId" : "594b9a764064e264420e3b53",
"TypeName" : "FD",
"Travel_Required" : true
}
]
}
}
我有很多文件,包含UnitID和TypeID(在Types对象中)的组合。我必须通过匹配UnitId和TypeID删除该Type元素。我用过$ pull但没有实现。
db.getCollection('units_details').update(
{ "UnitId" : "594b75d44064e264420e3870","Stream[0].Types.$.TypeID" : "594b9a884064e264420e3b56" },
{ $pull: { "Stream[0].Types"
"TypeId" : "594b9a884064e264420e3b56",
"TypeName" : "TR/RC",
"Travel" : false
} }} ,{multi:true}
);
如何实现删除类型数组中的类型,其中类型数组中的类型顺序正在发生变化。
答案 0 :(得分:1)
您可以使用以下任一查询来查询嵌套数组。
db.getCollection('units_details').update(
{"UnitId":"594b75d44064e264420e3870","Stream.Types.TypeId":"594b9a884064e264420e3b56"},
{"$pull":{
"Stream.$.Types":{
"TypeId":"594b9a884064e264420e3b56",
"TypeName":"TR/RC",
"Travel":false}
}},
{"multi":true}
);
OR(更适用于多标准方案)
db.getCollection('units_details').update( {
"UnitId":"594b75d44064e264420e3870",
"Stream":{
"$elemMatch":{
"Types":{
"$elemMatch":{"TypeId":"594b9a884064e264420e3b56"}
}
}
}
},
{"$pull":{
"Stream.$.Types":{
"TypeId":"594b9a884064e264420e3b56",
"TypeName":"TR/RC",
"Travel":false}
}},
{"multi":true}
)