get MongoDB ObjectId in JSON via Javascript - javascript

This is my JSON from PHP:
{"data" :
[
{
"_id" : {
"$id" : "4f977259b1445dce24000000"
},
"headline" : "asdfasdf",
"date" : {
"sec" : 1333584000,
"usec" : 0
},
"text":"asdfasdfas"
}
]
}
In Javascript I want to use the values and it works fine with
obj = JSON.parse(request);
console.log(obj.data[i].headline);
But how do I get the ObjectId?
It does not work like this:
console.log(obj.data[i]._id.$id);

It seems to work as expected when I try it http://jsfiddle.net/2CSWr/
console.log(json.data[0]._id.$id);​
does output the right value

This works for me:
console.log(obj.data[0]._id['$id']);

Related

Mongo script to update an object if its a certain value

I am trying to update a document in Mongo if it has a certain value within a field.
{
"_id" : ObjectId("myObject"),
"source" : "BW",
"sourceTableName" : "myTable",
"tableName" : "tier",
"type" : "main",
"fieldMappings" : [
{
"sourceField" : "tier_id", <~~~~ If this is "tier_id", I want to change it to "trmls_id"
"reportingField" : "bw_id",
"type" : "integer",
"defaultMap" : {
"shouldErrorOnConvert" : false
}
}
]
}
I tried something like
db.getCollection('entityMap').update({"sourceTableName":"myTable"}, {"fieldMappings.0.sourceField":"trmls_id":{$exists : true}}, { $set: { "fieldMappings.0.sourceField": "tier_id" } })
and I think it is failing on the $exists parameter I am setting.
Is there a more cleaner/dynamic way to do this?
The whole query I am trying to formulate is
In the table myTable
I want to check if there is a sourceField that has the value tier_id
If there is tier_id, then change it to trmls_id
Otherwise do nothing
If there is a similar StackOverflow question that answers this, I am happy to explore it! Thanks!
There is a syntax mistake and you can use positional operator $ in update part because you have already selector field in query part,
db.getCollection('entityMap').update(
{
"sourceTableName": "myTable",
"fieldMappings.sourceField": "tier_id" // if this field found then it will go to update part
},
{
$set: {
"fieldMappings.$.sourceField": "trmls_id"
}
}
)

How to find data within embedded documents array using id mongodb?

I am using mongodb with nodejs to find data in embedded document. strange fact is query works in database but not in actual nodejs code.
here is my data object:
{
"_id" : ObjectId("5c65866488a1c53464e46dc7"),
"cat_lang" : [
{
"_id" : ObjectId("5c65866488a1c53464e46dc8"),
"en" : "temp",
"it" : "temp"
}
],
"providers" : [
{
"_id" : ObjectId("5c65866488a1c53464e46dc9"),
"provider_name" : "temp0",
"url" : "http://uber.com",
},
{
"_id" : ObjectId("5c65866488a1c53464e46dca"),
"provider_name" : "temp1",
"url" : "http://uber2.com",
}
]}
I have tried these queries in the mongodb shell works perfectly fine.
db.sideservices.findOne({"_id" : ObjectId("5c65866488a1c53464e46dc7")},{providers: {$elemMatch: {"_id" : ObjectId("5c65866488a1c53464e46dca")}}})
AND
db.sideservices.find({"providers._id":ObjectId("5c65866488a1c53464e46dca")},{'providers.$':1})
But when using the same functions in nodejs, it returns the whole object instead document with the given id.
this.db.collection('sideservices').find({'providers':{'$elemMatch':{'_id':ObjectId('5c65866488a1c53464e46dca')}}}).toArray((err,res) => {...})
You can do this way
this.collection("sideservices").find({
"providers": { "$elemMatch": { "_id": ObjectId("5c65866488a1c53464e46dca") } }
})
.project({
"providers": { "$elemMatch": { "_id": ObjectId("5c65866488a1c53464e46dca") } }
})
.toArray((err,res) => {...})

Mongodb: get today's documents

I want to find all documents that have "fecha" equal than today's date (considering 'today' is 2017-08-08).
"Fecha" property is a string, so I tried this:
db.getCollection('operaciones').find({"fecha_registro": /^2017-08-08/});
It works good on robomongo so Ive been trying to send the "/^2017-08-08/" as a parameter to my api but no success.
Do you know a better way to achieve this? Maybe not send a parameter but use a function in mongo itself?
This are example documents:
{
"_id" : ObjectId("598910f600e65c6da6a9f643"),
"fecha" : "2017-08-08T01:16:38.783Z"
} {
"_id" : ObjectId("598910f600e65c6da6a9f644"),
"fecha" : "2017-08-08T01:23:21.183Z"
} {
"_id" : ObjectId("598910f600e65c6da6a9f645"),
"fecha" : "2017-08-09T01:52:31.313Z"
} {
"_id" : ObjectId("598910f600e65c6da6a9f646"),
"fecha" : "2017-08-09T04:36:01.512Z"
}
Thank you

MongoDB and Mongoose: How to retrieve nested Object

I have the following documents in my mongodb collection:
{
"current" :
{
"aksd" : "5555",
"BullevardBoh" : "123"
},
"history" :
{ "1" : {
"deleted" : false,
"added" : false,
"date" : "21-08-2014"
}
},
{ "2" : {
"deleted" : false,
"added" : false,
"date" : "01-01-2013"
}
},
"_id" : ObjectId("53f74dad2cbfdc136a07bf16"),
"__v" : 0
}
I have multiple of these documents. Now I want to achieve two things with my Mongoose/Express API.
Query for all nested "current" in each document and retrieve them as JSON objects like such: {"aksd":"5555","BullevardBoh":"123"},{..},{..}.
Retrieve all history revisions (1,2...) where "date" is smaller than a given date.
As you can clearly see this is a kind of versioning I am trying to implement. I would also be interested if this kind of data structure will get indexed by MongoDB and if there is possibly a better way. (e.g. with arrays inside objects?)
This isn't working in MongoDB:
db.ips.findOne({current.aksd: {$exists:true}});
I think the quotes around the field are missing here:
db.ips.findOne({current.aksd: {$exists:true}});
This should work instead:
db.ips.findOne({"current.aksd": {$exists:true}});
While Ritesh's reply was a step in the right direction, I rather wanted to fetch the current object literal and its members inside the document not the whole document.
1.) Query for all nested "current" in each document
db.ips.find({"current":{$exists:true}}, {"current":1});
This is giving back all nested documents where the aksd literal is present:
{ "current" : { "aksd" : "5555", "BullevardBoh" : "123" }, "_id" : ObjectId("53f74dad2cb3dc136a07bf16") }
...
2.) Retrieving history revisions where date is smaller then a given date:
db.ips.find({"history.date": {$lt: "01-01-2014"}},{history:{$elemMatch:{date: {$lt:"01-01-2014"}}}});
Giving back the wanted nested date literal(s):
{ "historie" : [ { "date" : "01-01-2013", "added" : false, "deleted" : false } ], "_id" : ObjectId("53faf20f399a954b2b7736b6") }

Mongo query in nested fields

I have a DB which has records with nested fields like :
"requestParams" : { "query" : [ "tv9" ] }
I am using the following query to fetch these kind of records. However I am looking for a more general case wherein the field query matches /tv9/ which includes tv9 as part of any search. Like it should also return livetv9, movietv9, etc. Following query does not seem to work:
db.requestLog.findOne({url : /search.json/, requestParams: {$elemMatch: {query: /tv9/}}})
$elemMatch is used to match partial document elements inside an array. Since you want to directly match on a string the use of this operator is inappropriate. Use this instead :
db.requestLog.findOne({url : /search.json/, 'requestParams.query': /tv9/})
Example :
mongos> db.test.save({r:{q:["tv9"]}})
mongos> db.test.save({r:{q:["tv"]}})
mongos> db.test.save({r:{q:["ltv9l"]}})
mongos> db.test.find({'r.q':/tv9/})
{ "_id" : ObjectId("4f5095d4ec991a74c16ba862"), "r" : { "q" : [ "tv9" ] } }
{ "_id" : ObjectId("4f5095deec991a74c16ba864"), "r" : { "q" : [ "ltv9l" ] } }

Categories