How to remove _id from MongoDB results? - mongodb

I am inserting json file into Mongodb(with Scala/Play framework) and the same getting/downloading it into my view page for some other requirement, but this time it is coming with one "_id" parameter in the json file.
But I need only my actual json file only that is not having any any "_id" parameter. I have read the Mongodb tutorial, that by default storing it with one _id for any collection document.
Please let me know that how can I get or is there any chance to get my actual json file without any _id in MongoDB.
this is the json result which is storing in database(I don't need that "_id" parameter)
{
"testjson": [{
"key01": "value1",
"key02": "value02",
"key03": "value03"
}],
"_id": 1
}

If you have a look at ReactiveMongo dev guide and to its API, you can see it support projection in a similar way as the MongoDB shell.
Then you can understand that you can do
collection.find(selector = BSONDocument(), projection = BSONDocument("_id" -> 0))
Or, as you are using JSON serialization:
collection.find(selector = Json.obj(), projection = Json.obj("_id" -> 0))

You can use this query in the shell:
db.testtable.find({},{"_id" : false})
Here we are telling mongoDB not to return _id from the collection.
You can also use 0 instead of false, like this:
db.testtable.find({},{"_id" : 0})
for scala you need to convert it in as per the driver syntax.

Related

mongodb query mixing timestamps and ISODates

I have a mongodb collection containing docs with both ISODates and timestamps in them, something like this:
doc = {
"_id" : ObjectId(...),
"updated" : 1445939778450,
"delivered" : ISODate("2016-12-21T09:40:29.082Z")
...
}
how can I compare updated and delivered fields using $where?
That's a great question! :)
It seems that mongodb handles this conversion automatically when using $where, so simply query like this:
db.my_collection.find({ $where : "this.updated > this.delivered" })
(if someone can point to documentation about this feature, please add)

Unable to get the value of a MongoDB key

2 days old to Mongo, so bear with me.
I have a collection from which, I only want to retrieve specific values contingent to another key existing in the MongoDB environment.
Here is what I am doing:
db.results.find({'someKeyThatShouldExist':{$exists:true}}, {"parentKey.childKey.theKeyWoseValueIwant":1}
This yields data in the following format for me:
{ "_id" : ObjectId("532a2c2b6803fa486b8b456a"), "parentKey" : { "childKey" : { "theKeyWhoseValueIWant" : 102982577 }}}.....
Now, all I really want is the value 102982577, not everything else.
How can I do this ?
You can suppress the _id by adding _id:0 to the projection criteria.
db.results.find(
{"someKeyThatShouldExist":{$exists:true}},
{_id:0, "parentKey.childKey.theKeyWoseValueIwant":1}
)
To get just the value, you could do something like:
db.results.find(
{"someKeyThatShouldExist":{$exists:true}},
{_id:0, "parentKey.childKey.theKeyWoseValueIwant":1}
)[0].parentKey.childKey.theKeyWoseValueIwant

How to query against ObjectId when not in mongo shell

I'm working on paging functionality using a range query. I'm using this test query in the mongo shell:
> var params = {$query: {_id: {$lt: ObjectId("52b06166eff887999c6efbd9")}}, $orderby: {_id: -1}, $maxScan: 3}
> params
{
"$query" : {
"_id" : {
"$lt" : ObjectId("52b06166eff887999c6efbd9")
}
},
"$orderby" : {
"_id" : -1
},
"$maxScan" : 3
}
> db.events.find(params)
I'd like to be able to pass the serialized params object to a web service (as a URL query string). However, the ObjectId class is only available inside the shell. Is there a way to specify an ObjectId as part of a query when not in the shell? I've tried the following as the value of $lt without success:
'ObjectId("52b06166eff887999c6efbd9")'
'new ObjectId("52b06166eff887999c6efbd9")'
{"$oid" : "52b06166eff887999c6efbd9"}
Generally speaking, this abstraction is handled by whatever MongoDB driver you use. If you are using an actual driver, you can do queries on _id without using ObjectId()
Mongoose / Node.js Example:
People.find({ _id : "Valid ObjectID String" }, function(e, person) {
console.log(e, person);
});
If you do still need the ObjectId helper, generally you are able to reference it in whatever native driver you need.
What you are doing in your last examples is passing your objectId as a string (first two examples) or as a dictionary third example. So surely it does not work.
You can pass just a string '52b06166eff887999c6efbd9' as a parameter and then when you receive it you can construct normal ObjectId on the server. For example in php you can construct it in the following way new MongoId('your string');

Mongoose: Saving as associative array of subdocuments vs array of subdocuments

I have a set of documents I need to maintain persistence for. Due to the way MongoDB handle's multi-document operations, I need to embed this set of documents inside a container document in order to ensure atomicity of my operations.
The data lends itself heavily to key-value pairing. Is there any way instead of doing this:
var container = new mongoose.Schema({
// meta information here
subdocs: [{key: String, value: String}]
})
I can instead have subdocs be an associative array (i.e. an object) that applies the subdoc validations? So a container instance would look something like:
{
// meta information
subdocs: {
<key1>: <value1>,
<key2>: <value2>,
...
<keyN>: <valueN>,
}
}
Thanks
Using Mongoose, I don't believe that there is a way to do what you are describing. To explain, let's take an example where your keys are dates and the values are high temperatures, to form pairs like { "2012-05-31" : 88 }.
Let's look at the structure you're proposing:
{
// meta information
subdocs: {
"2012-05-30" : 80,
"2012-05-31" : 88,
...
"2012-06-15": 94,
}
}
Because you must pre-define schema in Mongoose, you must know your key names ahead of time. In this use case, we would probably not know ahead of time which dates we would collect data for, so this is not a good option.
If you don't use Mongoose, you can do this without any problem at all. MongoDB by itself excels at inserting values with new key names into an existing document:
> db.coll.insert({ type : "temperatures", subdocuments : {} })
> db.coll.update( { type : "temperatures" }, { $set : { 'subdocuments.2012-05-30' : 80 } } )
> db.coll.update( { type : "temperatures" }, { $set : { 'subdocuments.2012-05-31' : 88 } } )
{
"_id" : ObjectId("5238c3ca8686cd9f0acda0cd"),
"subdocuments" : {
"2012-05-30" : 80,
"2012-05-31" : 88
},
"type" : "temperatures"
}
In this case, adding Mongoose on top of MongoDB takes away some of MongoDB's native flexibility. If your use case is well suited by this feature of MongoDB, then using Mongoose might not be the best choice.
you can achieve this behavior by using {strict: false} in your mongoose schema, although you should check the implications on the validation and casting mechanism of mongoose.
var flexibleSchema = new Schema( {},{strict: false})
another way is using schema.add method but i do not think this is the right solution.
the last solution i see is to get all the array to the client side and use underscore.js or whatever library you have. but it depends on your app, size of docs, communication steps etc.

querying on internals in mongo

I have document structure like:
{ "_id": { "$oid" : "51711cd87023380037000001" },
"dayData": "{ "daysdata":{"date":"02-12-2013","week_day":"","month":"","date_day":"","year":"2013"}}"
}
I want to extract document having date = "02-12-2013" in the above. Here i am trying to query on a value which is also a json.
Please let me know how to use mongodb java driver to extract this
Not answer (stackoverflow won't let me comment as I don't have enough points!)
Your string containing json has a syntax error.
There is a single " after "year":"2013"
You may have to fix that 1st.