I have a collection which stores a array of strings as a part of document and _id , is there a possibility that I can check the timestamp of any of the document which is logged.
the document structure is:
{ "_id" : NumberLong(1370891970), "k" : [ "argos","test"]}
Appreciate your help in advance.
-V
If this is your document structure, then there is no way to check it. None of your fields contains this information and you also overwrite your _id field.
Related
I am having Mongo Documents with duplicate Key,
{
"_id" : ObjectId("576a3b4a2bf2bc22bccb80ec"),
"Name" : "User1",
"Name" : "User2"
}
{
"_id" : ObjectId("576a3b4a2bf2bc22bccb80ab"),
"Name" : "User2",
"Name" : "User1"
}
When I try to query for Name as "User1". I always get one document only. But result should be two documents. Is there any way that I get correct result?
Thanks in advance
Note: I know my design is wrong I am just trying to make it success.
Please note that according to the docs, it IS possible to have duplicate key names, but depending on the driver you either might not be able to insert or read such data:
BSON documents may have more than one field with the same name. Most MongoDB interfaces, however, represent MongoDB with a structure (e.g. a hash table) that does not support duplicate field names. If you need to manipulate documents that have more than one field with the same name, see the driver documentation for your driver.
(Source: https://docs.mongodb.com/manual/core/document/#field-names)
Unfortunately, in order to correct your existing data, you will have to use a driver which can handle duplicate keys.
You cannot have two fields with same name in a collection in MongoDB .
When you try to insert a document with two fields with same key , MongoDB will update with the latest value rather than creating a separate fields.
Example :
db.test.insert({'Name':'user1','Name':'user2'})
db.test.insert({'Name':'user2','Name':'user1'})
Will result in inserting 2 documents as shown below
{ "_id" : ObjectId("576a8b4731157693143d0571"), "Name" : "user2" }
{ "_id" : ObjectId("576a8b5531157693143d0572"), "Name" : "user1" }
db.collection_name.find({"Name" : "User1"})
For a collection the ObjectId in MongoDB are unique because it acts as the primary key for that collection. As per the MongoDB Manual You can never have two documents in the same collection with same ObjectId.
But for different collections, there's a possibility of having the same ObjectID. And in that case while querying you obviously have to mention the collection name.
Hope this helps
I have a blogging system that stores uploaded files into the GridFS system. Problem is, I dont understand how to query it!
I am using Mongoose with NodeJS which doesnt yet support GridFS so I am using the actual mongodb module for the GridFS operations. There doesn't SEEM to be a way to query the files metadata like you do documents in a regular collection.
Would it be wise to store the metadata in a document pointing to the GridFS objectId? to easily be able to query?
Any help would be GREATLY appreciated, im kinda stuck :/
GridFS works by storing a number of chunks for each file. This way, you can deliver and store very large files without having to store the entire file in RAM. Also, this enables you to store files that are larger than the maximum document size. The recommended chunk size is 256kb.
The file metadata field can be used to store additional file-specific metadata, which can be more efficient than storing the metadata in a separate document. This greatly depends on your exact requirements, but the metadata field, in general, offers a lot of flexibility. Keep in mind that some of the more obvious metadata is already part of the fs.files document, by default:
> db.fs.files.findOne();
{
"_id" : ObjectId("4f9d4172b2ceac15506445e1"),
"filename" : "2e117dc7f5ba434c90be29c767426c29",
"length" : 486912,
"chunkSize" : 262144,
"uploadDate" : ISODate("2011-10-18T09:05:54.851Z"),
"md5" : "4f31970165766913fdece5417f7fa4a8",
"contentType" : "application/pdf"
}
To actually read the file from GridFS you'll have to fetch the file document from fs.files and the chunks from fs.chunks. The most efficient way to do that is to stream this to the client chunk-by-chunk, so you don't have to load the entire file in RAM. The chunks collection has the following structure:
> db.fs.chunks.findOne({}, {"data" :0});
{
"_id" : ObjectId("4e9d4172b2ceac15506445e1"),
"files_id" : ObjectId("4f9d4172b2ceac15506445e1"),
"n" : 0, // this is the 0th chunk of the file
"data" : /* loads of data */
}
If you want to use the metadata field of fs.files for your queries, make sure you understand the dot notation, e.g.
> db.fs.files.find({"metadata.OwnerId": new ObjectId("..."),
"metadata.ImageWidth" : 280});
also make sure your queries can use an index using explain().
As the specification says, you can store whatever you want in the metadata field.
Here's how a document from the files collection looks like:
Required fields
{
"_id" : <unspecified>, // unique ID for this file
"length" : data_number, // size of the file in bytes
"chunkSize" : data_number, // size of each of the chunks. Default is 256k
"uploadDate" : data_date, // date when object first stored
"md5" : data_string // result of running the "filemd5" command on this file's chunks
}
Optional fields
{
"filename" : data_string, // human name for the file
"contentType" : data_string, // valid mime type for the object
"aliases" : data_array of data_string, // optional array of alias strings
"metadata" : data_object, // anything the user wants to store
}
So store anything you want in the metadata and query it normally like you would in MongoDB:
db.fs.files.find({"metadata.some_info" : "sample"});
I know the question doesn't ask about the Java way of querying for metadata, but here it is, assuming you add gender as a metadata field:
// Get your database's GridFS
GridFS gfs = new GridFS("myDatabase);
// Write out your JSON query within JSON.parse() and cast it as a DBObject
DBObject dbObject = (DBObject) JSON.parse("{metadata: {gender: 'Male'}}");
// Querying action (find)
List<GridFSDBFile> gridFSDBFiles = gfs.find(dbObject);
// Loop through the results
for (GridFSDBFile gridFSDBFile : gridFSDBFiles) {
System.out.println(gridFSDBFile.getFilename());
}
metadata is stored in metadata field. You can query it like
db.fs.files.find({metadata: {content_type: 'text/html'}})
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.
I what to get document from mongodb ()and send it to the client as json object but without certain fields in mongoid document (for example without _id or other attributes).
What is the best way to accomplish the task?
Thanks!
You can decide what fields to select or deselect from the object while querying mongodb.
You can mention them as a parameter while querying.
http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-FieldNegation
example:
db.myCollection.find( { age : 20 }, { _id : 0 } ); // omit the _id field in result
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?