如何从Mongodb/mongoose中的对象内部存在的数组中删除元素 [英] How to Delete an element from the array which is present inside an object in Mongodb/mongoose
问题描述
以下是对话"集合的文档结构
Here is the struncture of a document of the collection 'conversations'
{
"_id" : ObjectId("553778c0d3adab10206060db"), //conversation id
"messages" : [
{
"from" : ObjectId("5530af38576214dd3553331c"),
"_id" : ObjectId("553778c0d3adab10206060dc"),//message id
"created" : ISODate("2015-04-22T10:32:32.056Z"),
"read" : false,
"message" : "second object first msg",
"participants" : [
ObjectId("5530af38576214dd3553331c"), //participant id
ObjectId("553777f2d3adab10206060d8")//participant id
]
},
{
"from" : ObjectId("5530af38576214dd3553339b"),
"_id" : ObjectId("553778c0d3adab10206060dc"),//message id
"created" : ISODate("2015-04-22T10:32:32.059Z"),
"read" : false,
"message" : "second object second msg",
"participants" : [
ObjectId("5530af38576214dd3553331c"),//participant id
ObjectId("553777f2d3adab10206060d8")//participant id
]
}
],
"participants" : [
ObjectId("5530af38576214dd3553331c"),
ObjectId("553777f2d3adab10206060d8")
],
"__v" : 0
}
每个文档都包含消息"数组,该数组又包含消息对象作为数组元素.每个对象都有参与者数组.
Each document contains 'messages' array which in turn contains messages objects as array elements. Each object has participants array.
我有对话ID,消息ID,参与者ID.
I am having conversation id , message id , participant id.
我想从参与者"数组(消息"数组的消息对象中存在的参与者"数组)中删除特定元素. 我尝试了这段代码.
I want to delete a particular element from the 'participants' array( the 'participants' array which is present in the message object of the 'messages' array). I tried this code.
var query = { _id: mongoose.Types.ObjectId(req.conversation.id), 'messages._id':req.params.messageId};
Conversation.findOneAndUpdate(query, {$pull: {'participants' : participant_id}}, function(err, data){})
但是它正在从外部参与者"数组中删除对象元素. 请帮助我完成此操作.
But it is deleting the object element from the outer 'participants' array. Please help me to get this done.
谢谢
推荐答案
检查mongo 位置运算符,查询如下:
Check mongo positional operator, query as below :
db.conversations.update({
"_id": ObjectId("553778c0d3adab10206060db"),
"messages": {
"$elemMatch": {
"_id": ObjectId("553778c0d3adab10206060dc")
}
},
"messages": {
"$elemMatch": {
"participants": {
"$in": [ObjectId("5530af38576214dd3553331c")]
}
}
}
}, {
"$pull": {
"messages.$.participants": {
"$in": [ObjectId("5530af38576214dd3553331c")]
}
}
})
这将从匹配的message
数组中删除给定的participants
对象.希望如此对您有帮助,您应该将其转换为猫鼬.
This remove given participants
object from matching message
array. And hope so this will help you and you should convert it into mongoose.
这篇关于如何从Mongodb/mongoose中的对象内部存在的数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!