MongoDB - Create object with reference manually - DBRef doesn't work - mongodb

for testing purposes I need to create manually some objects in a MongoDB. My Class has a reference field to another class. The referred object already exists.
I tried to put the Mongo-ID of my existing object as a value in my new object but I get the following error:
A ReferenceField only accepts DBRef: ['attribute'])
Now my question: Where do I get or find this DBRef?
An example:
I have a user in my db. I want to create a group which has the existing user as "creator". When I put the user-ID into the creator-field I get the error...
Edit:
I just found this link MongoDB - DBRef but the solution does not work for me...
item : {"$ref" : "fruit", "$id" : "1"}
My code is like this:
{ "name" : "MyGroup", "created_at" : "2011-05-22T00:46:38", "creator": { "$ref": "user", "$id": "501bd5ac32f28a1278e54435" } }
Another edit:
Even the Mongo doc says I'm using the right format... http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON. But still not working.

In the question you referenced, the user is using a numeric string as their document ID. In your case, it looks like you're working with the more-common ObjectId but inserting it as a string. Assuming you're using PyMongo, you probably want to use the ObjectId class for the $id property of the DBRef.
If you know all such references are going to point to the same DB and collection, it may make sense to use manual references (just storing the target document's _id) instead of DBRef objects. This is explained in more detail in the Database References documentation.

Related

Using "id" in addition to "_id" in a Document Model

I've created a document model where I'm using a field named id in addition to MongoDB's auto-generated _id field.
Will this cause any problems for me down the line?
I can imagine a circumstance where something in Mongo might assume my "id" property is referring to "_id" instead, when it isn't (like some API feature with the good intention of preventing you from having to type that underscore, where in my case such a well-meaning feature would be a disaster).
Will this be ok?

create new collection in mongodb by adding index in system.indexes

when I attempt to insert new document manually in system.indexes collection in mongodb,new collection created.here goes the code
{
"v" : 1,
"key" : {
"code" : 1
},
"name" : "code_1",
"ns" : "mydb.collection"
}
where collection is my collection name which is not already present in database and mydb is my database name. Why new collection is getting created?
Is it possible to create collection by adding index manually in system.indexes.
Why are you asking us this? You already tried to add a new index to system.indexes. Has a new collection been created? If yes, then yes it is possible, if no, then not possible.
Is this a correct way?
How do you think? Have you read somewhere in documentation that in order to create a new collection you need to dance around and to create manually indexes in some system defined collection? Or may be it was written in documentation that db.createCollection(name, options) is what you should do or if you so desire you can just insert a document in a non existed collection and it will create it.
So why after all this one might think that the correct way is to do some manipulation with system.indexes?
As a complement to #Salvador Dali's answer strongly discouraging you to do modify system.index directly: if for some reason you really don't want/can't use createCollection, just remember this is a wrapper around the create command.
You can issue yourself such command to create a new collection:
db.runCommand( { create: "collection" } )
As about inserting an entry in system.indexes: from the doc:
Deprecated since version 3.0: Access this data using listIndexes.
The <database>.system.indexes collection lists all the indexes in the database.
By reading that it appears that system.indexes should be considered as read-only (its direct use is even deprecated since 3.0). The behavior you observed should be considered as unspecified. And so unreliable and subject to change without further notices.
If you really need to understand why it behave that way, maybe you should take a look at the source code or ask the question on the MongoDB developer mailing list. There you could have all the insights.

Denormalization Data in MongoDb Doctrine Symfony 2

I'm Following this Doc
http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/tutorials/getting-started.html
And
http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html
When I Save My Document, I have two Collection
like this:
{
"_id" : ObjectId("5458e370d16fb63f250041a7"),
"name" : "A Foo Bar",
"price" : 19.99,
"posts" : [
{
"$ref" : "Embedd",
"$id" : ObjectId("5458e370d16fb63f250041a8"),
"$db" : "test_database"
}
]
}
I'd like have
{
"_id" : ObjectId("5458e370d16fb63f250041a7"),
"name" : "A Foo Bar",
"price" : 19.99,
"posts" : [
{
"mycomment" :"dsdsds"
" date" : date
}
]
}
I want denormalization my data. How Can i Do it?
Can I use Methods like $push,$addToSet etc of mongoDb?
Thanks
Doctrine ODM supports both references and embedded documents.
In your first example, you're using references. The main document (let's assume it's called Product) references many Post documents. Those Post documents live in their own collection (for some reason this is named Embedd -- I would suggest renaming that if you keep this schema). By default, ODM uses the DBRef convention for references, so each reference is itself a small embedded document with $ref, $id, and $db fields.
Denormalization can be achieved by using embedded documents (an #EmbedMany mapping in your case). If you were embedding a Post document, the Post class should be mapped as an #EmbeddedDocument. This tells ODM that it's not a first-class document (belonging to its own collection), so it won't have to worry about tracking it by _id and the like (in fact, embedded documents won't even need identifiers unless you want to map one).
My rule of thumb for deciding to embed or references has generally been asking myself, "Will I need this document outside of the context of the parent document?" If a Post will not have an identity outside of the Product record, I'm comfortable embedding it; however, if I find later that my application also wants to show users a list of all of their Posts, or that I need to query by Posts (e.g. a feed of all recent Posts, irrespective of Product), then I may want to reference documents in a Posts collection (or simply duplicate embedded Posts as needed).
Alternatively, you may decide that Posts should exist in both their own collection and be embedded on Product. In that case, you can create an AbstractPost class as a #MappedSuperclass and define common fields there. Then, extend this with both Post and EmbeddedPost sub-classes (mapped accordingly). You'll be responsible for creating some code to generate an EmbeddedPost from a Post document, which will be suitable for embedding in the Product.posts array. Furthermore, you'll need to handle data synchronization between the top-level and embedded Posts (e.g. if someone edits a Post comment, you may want all the corresponding embedded versions updated as well).
On the subject of references: ODM also supports a simple option for reference mappings, in which case it will just store the referenced document's _id instead of the larger DBRef object. In most cases, having DBRef store the collection and database name for each referenced document is quite redundant; however, DBRef is actually useful if you're using single-collection inheritance, as ODM uses the object to store extra discriminator information (i.e. the class of the referenced object).

How can i change _id field in MongoDB Collection to User_id?

I am new user for MongoDB Database. In MongoDb whatever insert into some collection defaultly one field is added that is _id field.
For Example:
db.users.insert({"User_id":"1","User_Name":"xxx","Address":"yyyy"})
db.users.find()
It shows
{ "_id" : ObjectId("528475fc326b403f580d2eba"), "User_id" : "1", "User_Name" : "xxx",Address" : "yyyy" }
I don't need _id field and i want to replace that _id field to User_id with auto increment values.
Is it possible. Please help me. Thanks in advance.
_id field is really special in mongodb. This is your primary key there and there is no way you can have a document without it. Even if you are trying to insert the document without it, mongo will create it for you (as in your example). Moreover, you can not even modify _id field for you collection.
But you can create a document with your own _id. So if you want you can do db.users.insert({"_id":"1","User_Name":"xxx","Address":"yyyy"}) \\why exactly 1 is a string?
and remember that _id means user_id and also keep in mind that this _id should be unique
Keep in mind that mongodb is not like sql. It does not have autoincrement keys (by this I mean that it is not that creators did not know how to do it, but just that you can leave pretty much without it), but you can achieve create something that would resemble the same behaviour.
As for as I can understand your problem is that you want to use your mongoDB internal _id as your custom attribute. For example suppose the db contain the user Identity and having attributes like "_id , name , address ..." and you want to use this _id's value in your application as userId for external reference.
So as #SalvadorDali said _id field is really important in the mongoDB and you can not have a document without it. All you can do is let the db store the value by it's default _id but you can access outside using your own User_id by applying these two changes in your json file.
"properties": {
"userId":{
"type": "string",
"id":"true",
"index":"true",
"description": "unique id of identity"
}
}
now you store any unique value, it is stored in the db using default _id and outside you can have that value in userId field.
Correct me if i got your question wrong.

MongoDB - DBRef to a DBObject

Using Java ... not that it matters.
Having a problem and maybe it is just a design issue.
I assign "_id" field to all of my documents, even embedded ones.
I have a parent document ( and the collection for those ) which has an embedded document
So I have something like:
{ "_id" : "49902cde5162504500b45c2c" ,
"name" : "MongoDB" ,
"type" : "database" ,
"count" : 1 ,
"info" : { "_id" : "49902cde5162504500b45c2y",
"x" : 203 ,
"y" : 102
}
}
Now I want to have another document which references my "info" via a DBRef, don't want a copy. So, I create a DBRef which points to the collection of the parent document and specifies the _id as xxxx5c2y. However, calling fetch() on the DBRef gives a NULL.
Does it mean that DBRef and fetch() only works on top level collection entry "_id" fields?
I would have expected that fetch() would consume all keys:values within the braces of the document .. but maybe that is asking too much. Does anyone know?? Is there no way to create cross document references except at the top level?
Thanks
Yes, your DBRef _id references need to be to documents in your collection, not to embedded documents.
If you want to find the embedded document you'll need to do a query on info._id and you'll need to add an index on that too (for performance) OR you'll need to store that embedded document in a collection and treat the embedded one as a copy. Copying is OK in MongoDB ... 'one fact one place' doesn't apply here ... provided you have some way to update the copy when the main one changes (eventual consistency).
BTW, on DBRef's, the official guidance says "Most developers only use DBRefs if the collection can change from one document to the next. If your referenced collection will always be the same, the manual references outlined above are more efficient."
Also, why do you want to reference info within a document? If it was an array I could understand why you might want to refer to individual entries but since it doesn't appear to be an array in your example, why not just refer to the containing document by its _id?