This question already has answers here:
MongoDb: Benefit of using ObjectID vs a string containing an Id?
(3 answers)
Closed 8 years ago.
I need to store reference to other collection and I can't decide if I should store it as a string, or as an ObjectId(). I see it is possible do it in both ways (in mongo shell):
As an ObjectId
db.books.findOne({_id:ObjectId("54bc1287c582714e9f062591")});
{
"_id" : ObjectId("54bc1287c582714e9f062591"),
"title" : "Book title",
"author_id" : ObjectId("54bc12da5f5e8854718b4568")
}
As a string
db.books.findOne({_id:ObjectId("54bc1287c582714e9f062591")});
{
"_id" : ObjectId("54bc1287c582714e9f062591"),
"title" : "Book title",
"author_id" : "54bc12da5f5e8854718b4568"
}
I will not be searching by author_id, so I don't need any index there. I'll take a book, and then will take an author by author_id. By the way, it is just an example with books
The major difference is that an ObjectId will take up 12 bytes space (http://docs.mongodb.org/manual/reference/object-id/) while the string representation takes 24 bytes. Thus, using ObjectId's will save you half the space.
Related
I have a very basic (might be sily) question.
Suppose I am having product collection with list of product as below.
db.products.findOne
{
"_id" : ObjectId("60db1b449f9a43695c4bb461"),
"name" : "product 1"
}
while storing category as a relation, how should it be stored? (Please check the category_id)
approach 1
db.products.findOne
{
"_id" : ObjectId("60db1b449f9a43695c4bb461"),
"name" : "product 1",
"category_id" : ObjectId("608f981fcfeaa757ca69b4b5")
}
approach 2
db.products.findOne
{
"_id" : ObjectId("60db1b449f9a43695c4bb461"),
"name" : "product 1",
"category_id" : "608f981fcfeaa757ca69b4b5"
}
It depends.
Embed as ObjectId type if:
You will perform $lookUp operations based on this key, then it's better to embed it as ObjectId type.
I highly recommend embedding it as ObjectId
Embed as string type if:
The driver or application which you are using does not support working with the ObjectId type.
In the company I am working for, we have embedded relations as ObjectId, and even though it's easy to pass the data to REST API (since no conversion is needed), it's a big pain to convert string to ObjectId for $lookUp operations.
Note that in most of the languages, you have to handle errors additionally while converting string to ObjectId (since ObjectId has validation rules), whereas this problem is not present for converting ObjectId to string
This question already has answers here:
How to sort array inside collection record in MongoDB?
(16 answers)
mongodb group values by multiple fields
(4 answers)
Update Array Children Sorted Order
(2 answers)
Closed 5 years ago.
I have written mongo query with node.js.
I have array object in my document. I want to apply pagination & sort on that array.
"user_notifications" : [
{
"_id" : ObjectId("59a7c30ecd6109c914c5fb5f"),
"notification_on" : ISODate("2017-09-28T10:00:44.828+0000"),
"procedure_id" : "59ccc84c1312ac3756944736"
},
{
"_id" : ObjectId("59db55ed57983b04534f0285"),
"notification_on" : ISODate("2017-10-09T10:56:45.235+0000"),
"procedure_id" : "59db55ed57983b04534f024d"
},
{
"_id" : ObjectId("59db672b9700ef5f54f25b3a"),
"procedure_id" : "59db672b9700ef5f54f25b0a",
"notification_on" : ISODate("2017-10-09T12:10:19.900+0000")
},
{
"_id" : ObjectId("59db694f89cb7e9954af26ad"),
"notification_on" : ISODate("2017-10-09T12:19:27.954+0000"),
"procedure_id" : "59db694f89cb7e9954af267d"
}
]
I want to sort “user_notification” array using “notification_on” key. I have used following code for pagination which is perfectly working fine.
UserModel.findOne({"_id":user._id},{user_notifications:{$slice:[skip,
limit]}}, function(err , user_obj){
.
.
.
});
But I am unable to sort records.
This question is different than other because I am retrieving only one record which has "user_notifications" object. I wanted to apply pagination for objects in this array & this array needs to sort by notification_on key.
Thanks
This question already has answers here:
MongoDB Query Help - query on values of any key in a sub-object
(3 answers)
Closed 6 years ago.
I have the following structure :
{
"FiledA" : "FiledAValue",
"FiledB" : "FiledBValue",
"FiledC" : {
"X" : "XValue",
"Y" : "YValue",
"Z" : "ZValue"
},
}
FiledC content may be dynamic (other fileds than x,y,z)
The user will send a query like {"FiledA" : "12" , "FiledC" : "333"}
The query should match 12 for FiledA and if there any FiledC which one of its filds contains 333
How I can solve the FiledC issue in a query ?
Thanks in advance ...
You should not use dynamic fields to query. It is not possible to query on these fields without individually inspecting all the fields. The similar approach has been exemplified at this answer
If you are open to changing your schema, I would recommend changing it to :
{
FieldC:[
{name:"X", value:"value1"},
{name:"Y", value:"value2"},
{name:"Z", value:"value3"}
]
}
You can now query using :
db.collection.find({"FieldC.value":"testValue"});
Am looking to build a blogging system and came across the following blog.
http://blog.mongolab.com/2012/08/why-is-mongodb-wildly-popular/
While it's nice to see how we can store everything in one Mongo document as a json type object (example json from the blog pasted below) rather than distributing data across multiple tables, I'm having trouble understanding how this can accommodate an hypothetically super long comment thread.
{
_id: 1234,
author: { name: "Bob Davis", email : "bob#bob.com" },
post: "In these troubled times I like to …",
date: { $date: "2010-07-12 13:23UTC" },
location: [ -121.2322, 42.1223222 ],
rating: 2.2,
comments: [
{ user: "jgs32#hotmail.com",
upVotes: 22,
downVotes: 14,
text: "Great point! I agree" },
{ user: "holly.davidson#gmail.com",
upVotes: 421,
downVotes: 22,
text: "You are a moron" }
],
tags: [ "Politics", "Virginia" ]
}
Aside from the comments key which is represented as an array of comment objects, allowing us to store an endless number of comments within this document rather than on a separate comments table requiring a join operation to relate if we are to do this with a relational database, the rest of the fields (ie author, post, date, location, rating, tags) can all be done as columns on a relational database table as well.
Since there is a limit of 16MB per document, what happens when this blog attracts a lot of comments?
Also, why can't I store a json object on a relational database column? Afterall it's a text isn't it?
First, a clarification: MongoDB actually stores BSON, which is a essentially superset of JSON that supports more data types.
Since there is a limit of 16MB per document, what happens when this blog attracts a lot of comments?
You won't be able to increase the size past 16MB, so you'll lose the ability to add more comments. But you don't need to store all the comments on the blog post document. You could store the first N, then retire old comments to a comments collection as new ones are added. You could store comments in another collection with a parent reference. The way comments are stored should jive with how you expect them to be used. 16MB of comments would really be a lot - you might even have a special solution to handle the occasional post that gets that kind of activity, an approach that's totally different from the normal way of handling comments.
We can store json in a relational database. So what is the value of Mongo I'm getting?
Here's two ways of storing JSON (in MongoDB).
> db.test.drop()
> db.test.insert({ "name" : { "first" : "Yogi", "last" : "Bear" }, "location" : "Yellowstone", "likes" : ["picnic baskets", "PBJ", "the great outdoors"] })
> db.test.findOne()
{
"_id" : ObjectId("54f9f41f245e945635f2137b"),
"name" : {
"first" : "Yogi",
"last" : "Bear"
},
"location" : "Yellowstone",
"likes" : [
"picnic baskets",
"PBJ",
"the great outdoors"
]
}
var jsonstring = '{ "name" : { "first" : "Yogi", "last" : "Bear" }, "location" : "Yellowstone", "likes" : ["picnic baskets", "PBJ", "the great outdoors"] }'
> db.test.drop
> db.test2.insert({ "myjson" : jsonstring })
> db.test2.findOne()
{
"_id" : ObjectId("54f9f535245e945635f2137d"),
"myjson" : "{ \"name\" : { \"first\" : \"Yogi\", \"last\" : \"Bear\" }, \"location\" : \"Yellowstone\", \"likes\" : [\"picnic baskets\", \"PBJ\", \"the great outdoors\"] }"
}
Can you store and use JSON the first way using a relational database? How useful is JSON stored in the second way compared to the first?
There's lots of other differences between MongoDB and relational databases that make one better than the other for various use cases - but going further into that is too broad for an SO answer.
Can you store and use JSON the first way using a relational database?
How useful is JSON stored in the second way compared to the first?
Sorry are you suggesting that with Mongo json documents can be stored without using escape characters, whereas with a RDBMS I must use escape characters to escape the double quotes? I wasn't aware of that's the case.
HI I have following data items in mongo db
{ "id" : 950, "name" : "Name 1" },
{ "id" : 951, "name" : "name 2" }
I have tried mapping id as both Integer and String.
and I used morphia + play to connect mongodb and used DAO of morphia.
I need to do a search by id like (in sql where id like '95%' ) and get the result as list.
List pList = ds.createQuery(Person.class).field("id").startsWith("95").asList(); // this is not working
Any ideas how get this done ??
Having already answered on the play mailing list and the morphia list, i'll answer here so others will see it, too. startsWith() is a text based operation. It doesn't work against numbers. you'll have to use a greaterThan/lessThan query for range checking.