Mongodb删除内嵌数组指定对象

官方解释:

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




你可能感兴趣的:(mongo)