MongoDB - DBRef

自古美人都是妖i 提交于 2019-12-02 09:04:53

Syntax for the dbref is

  { $ref : <collname>, $id : <idvalue>[, $db : <dbname>] }

But you have added non-supported quantity field inside dbref. Thats the problem. take that outside

db.basket.save ({"_id" : "1", "items" : [
    {"quantity" : 5 , item : {"$ref" : "fruit", "$id" : "1"}},
    {"quantity" : 10, item : {"$ref" : "fruit", "$id" : "3"}}
]})

which kind of looks (scary)

{
    "_id" : "1",
    "items" : [
        {
            "quantity" : 5,
            "item" : {
                "$ref" : "fruit",
                "$id" : "1"
            }
        },
        {
            "quantity" : 10,
            "item" : {
                "$ref" : "fruit",
                "$id" : "3"
            }
        }
    ]
}

But my advice is, ditch the dbref altogether and just use the simple structure like this

db.basket.save ({"_id" : "1",items:[
                        {item_id:"1",quantity:50},
                        {item_id:"3",quantity:10}
                ]})

this is much cleaner, which will look like

{
    "_id" : "1",
    "items" : [
        {
            "item_id" : "1",
            "quantity" : 50
        },
        {
            "item_id" : "3",
            "quantity" : 10
        }
    ]
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!