官方解释:
The $pull operator removes all instances of a value from an existing array, as in the following prototype:
db.collection.update( { field: <query> }, { $pull: { field: <query> } } );
当数组中的值为字符串或数字时,用pull或pullAll很方便,field后面的值直接跟上数组中的值即可。如果数组中的值为对象时,其实也很简单,field后跟上对象中条件字段和值即可。
e.g.:
db.test.find({"msgid":170}).toArray()
[
{
"_id" : ObjectId("52fd7abe5cf0fb00ee4775bf"),
"msgid" : NumberLong(170),
"msg" : [
{
"comcont" : "heddhefasdfa",
"comtime" : NumberLong(1392346547)
},
{
"comcont" : "heddhefasdfa",
"comtime" : NumberLong(1392346667)
}
]
}
]
删除comtime为1392346547的对象。
db.test.update({"msgid":170},{"$pull":{"msg":{"comtime":1392346547}}})
db.test.find({"msgid":170}).toArray()
[
{
"_id" : ObjectId("52fd7abe5cf0fb00ee4775bf"),
"msgid" : NumberLong(170),
"msg" : [
{
"comcont" : "heddhefasdfa",
"comtime" : NumberLong(1392346667)
}
]
}
]
之前试了很多方法都不对,原来是pull用法写的不对。
参考文献:
http://stackoverflow.com/questions/15641492/mongodb-remove-object-from-array
这篇博客介绍了如何使用$pull操作符从MongoDB的内嵌数组中删除指定对象。当数组元素为字符串或数字时,直接提供值即可;若为对象,则需指定对象的条件字段和值。示例中展示了删除comtime为1392346547的对象,并提到了在尝试删除时的常见错误。参考了StackOverflow上的相关问题解答。
1万+

被折叠的 条评论
为什么被折叠?



