0

I am having some troubles with DBRef, look this case:

db.fruit.save ({"_id" : "1" , "name" : "apple"});
db.fruit.save ({"_id" : "2" , "name" : "grape"});
db.fruit.save ({"_id" : "3" , "name" : "orange"});
db.fruit.save ({"_id" : "4" , "name" : "pineapple"});

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

Now, lets find the "basket" collection:

> db.basket.find ()
{ "_id" : "1", "items" : [
    {
        "$ref" : "fruit",
        "$id" : "1"
    },
    {
        "$ref" : "fruit",
        "$id" : "3"
    }
] }

The "quantity" attribute disappeared ?! Anybody knows why ? Is there an alternative ?

Thanks.

Caio
  • 3,178
  • 6
  • 37
  • 52

1 Answers1

8

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
        }
    ]
}
RameshVel
  • 64,778
  • 30
  • 169
  • 213
  • 1
    but with the last approach, how can i get all the items data, like a join? – jtomasrl Nov 08 '12 at 15:12
  • 1
    Just to clarify, additional fields are supported within a DBRef, since it really is just a BSON object; however, the MongoDB shell hides fields other than `$ref`, `$id`, and the optional `$db` field when rendering the value. Some ODMs actually store additional values in a DBRef object (Doctrine does this with class discriminator values). That said, you are certainly better off without a DBRef if you are always referring to objects in the same database and collection, as `$ref` and `$db` are useless overhead in that case. – jmikola Sep 11 '14 at 17:05