如何删除mongoDB中的子记录

时间:2012-09-14 09:17:46

标签: node.js mongodb

我有一个类似的数据库:

{
    "_id": ObjectId("50525e55467f67da3f8baf06"),
    "client": "client1"
}{
    "_id": ObjectId("505262f0deed32a758410b1c"),
    "client": "client2"
}{
    "_id": ObjectId("505269e2062dae91946e3c26"),
    "client": "client3"
}{
    "_id": ObjectId("5052f469341bdc4e8ac1b226"),
    "client": "client4",
    "products": [
        {
            "name": "product1"
        },
        {
            "name": "product2"
        }
    ]
}

我的问题是,如何在不删除client4记录的情况下从client4的产品列表中删除product2?输出应如下所示:

{
    "_id": ObjectId("50525e55467f67da3f8baf06"),
    "client": "client1"
}{
    "_id": ObjectId("505262f0deed32a758410b1c"),
    "client": "client2"
}{
    "_id": ObjectId("505269e2062dae91946e3c26"),
    "client": "client3"
}{
    "_id": ObjectId("5052f469341bdc4e8ac1b226"),
    "client": "client4",
    "products": {
        "name": "product1"
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用$pull

db.coll.update({client:'client4'},{$pull : { products : { name : 'product1' }});