MongoDB - eval Vs. db.eval - javascript

I have a simple stored script in system.js collection called getAllNotes.
script code: function (x) { return db.notes.find(); }
notes is a collection holding the data I wish to extract.
eval('getAllNotes()') - works well and returns the data.
db.eval('getAllNotes()') - returns a JSON string with various configuration that has nothing to do
with my collection See below. Any idea? anyone understands the difference between executing eval and db.eval?
"_mongo" : {
"slaveOk" : false,
"host" : "EMBEDDED"
},
"_db" : {
"_mongo" : {
"slaveOk" : false,
"host" : "EMBEDDED"
},
"_name" : "test"
},
"_collection" : {
"_mongo" : {
"slaveOk" : false,
"host" : "EMBEDDED"
},
"_db" : {
"_mongo" : {
"slaveOk" : false,
"host" : "EMBEDDED"
},
"_name" : "test"
},
"_shortName" : "notes",
"_fullName" : "test.notes"
},
"_ns" : "test.notes",
"_query" : {
},
"_fields" : null,
"_limit" : 0,
"_skip" : 0,
"_batchSize" : 0,
"_options" : 0,
"_cursor" : null,
"_numReturned" : 0,
"_special" : false

eval takes a string of code that it executes.
db.eval, according to the docs, takes a function to call and a list of parameters to pass to that function. In other words, leave off the single quotes ' here:
db.eval(getAllNotes())
As for the difference between the two, the docs also state it:
The helper db.eval() in the mongo shell wraps the eval command. Therefore, the helper method shares the characteristics and behavior of the underlying command with one exception: db.eval() method does not support the nolock option.
Docs. Important stuff to learn things from before asking other people to do it for you.

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"
}
}
)

mongoose index already exists with different options

I am implementing search result view to my app.
I figured out that mongoose internally provide full text search function with $text.
I put the code below to Post.js
PostSchema.index({desc: 'text'}); //for example
Here's the code I put in my routing file route/posts.js
Post.find({$text: {$search : 'please work!'}}).exec(function (err, posts) {...})
The error message I come up with is below
Index with pattern: { _fts: "text", _ftsx: 1 } already exists with different options
Would there any body who know how to deal with this error and figure out?
Thanks you.
check on which field you have your text index defined. Right now mongodb allows only one text index per collection. so if you have defined a text index on desc column and try to use that index on some other column you are bound to get this error.
can you try to query your index and see on which column you created it. To get indexes you can do
db.collection.getIndexes()
and it will return something like this
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "some.ns"
},
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "desc_text",
"ns" : "some.ns",
"weights" : {
"title" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 2
}
]
now if you want to scope in other columns also to use this index simply drop this index
db.collection.dropIndex('desc_text');
and then recreate it by including all columns you want to be covered by text index,
db.collection.createIndex({
title:'text;,
body: 'text;,
desc: 'text',
...... and so on
});

Meteor: Return only single object in nested array within collection

I'm attempting to filter returned data sets with Meteor's find().fetch() to contain just a single object, it doesn't appear very useful if I query for a single subdocument but instead I receive several, some not even containing any of the matched terms.
I have a simple mixed data collection that looks like this:
{
"_id" : ObjectId("570d20de3ae6b49a54ee01e7"),
"name" : "Entertainment",
"items" : [
{
"_id" : ObjectId("57a38b5f2bd9ac8225caff06"),
"slug" : "this-is-a-long-slug",
"title" : "This is a title"
},
{
"_id" : ObjectId("57a38b835ac9e2efc0fa09c6"),
"slug" : "mc",
"title" : "Technology"
}
]
}
{
"_id" : ObjectId("570d20de3ae6b49a54ee01e8"),
"name" : "Sitewide",
"items" : [
{
"_id" : ObjectId("57a38bc75ac9e2efc0fa09c9"),
"slug" : "example",
"name" : "Single Example"
}
]
}
I can easily query for a specific object in the nested items array with the MongoDB shell as this:
db.categories.find( { "items.slug": "mc" }, { "items.$": 1 } );
This returns good data, it contains just the single object I want to work with:
{
"_id" : ObjectId("570d20de3ae6b49a54ee01e7"),
"items" : [
{
"_id" : ObjectId("57a38b985ac9e2efc0fa09c8")
"slug" : "mc",
"name" : "Single Example"
}
]
}
However, if a similar query within Meteor is directly attempted:
/* server/publications.js */
Meteor.publish('categories.all', function () {
return Categories.find({}, { sort: { position: 1 } });
});
/* imports/ui/page.js */
Template.page.onCreated(function () {
this.subscribe('categories.all');
});
Template.page.helpers({
items: function () {
var item = Categories.find(
{ "items.slug": "mc" },
{ "items.$": 1 } )
.fetch();
console.log('item: %o', item);
}
});
The outcome isn't ideal as it returns the entire matched block, as well as every object in the nested items array:
{
"_id" : ObjectId("570d20de3ae6b49a54ee01e7"),
"name" : "Entertainment",
"boards" : [
{
"_id" : ObjectId("57a38b5f2bd9ac8225caff06")
"slug" : "this-is-a-long-slug",
"name" : "This is a title"
},
{
"_id" : ObjectId("57a38b835ac9e2efc0fa09c6")
"slug" : "mc",
"name" : "Technology"
}
]
}
I can then of course filter the returned cursor even further with a for loop to get just the needed object, but this seems unscalable and terribly inefficient while dealing with larger data sets.
I can't grasp why Meteor's find returns a completely different set of data than MongoDB's shell find, the only reasonable explanation is both function signatures are different.
Should I break up my nested collections into smaller collections and take a more relational database approach (i.e. store references to ObjectIDs) and query data from collection-to-collection, or is there a more powerful means available to efficiently filter large data sets into single objects that contain just the matched objects as demonstrated above?
The client side implementation of Mongo used by Meteor is called minimongo. It currently only implements a subset of available Mongo functionality. Minimongo does not currently support $ based projections. From the Field Specifiers section of the Meteor API:
Field operators such as $ and $elemMatch are not available on the client side yet.
This is one of the reasons why you're getting different results between the client and the Mongo shell. The closest you can get with your original query is the result you'll get by changing "items.$" to "items":
Categories.find(
{ "items.slug": "mc" },
{ "items": 1 }
).fetch();
This query still isn't quite right though. Minimongo expects your second find parameter to be one of the allowed option parameters outlined in the docs. To filter fields for example, you have to do something like:
Categories.find(
{ "items.slug": "mc" },
{
fields: {
"items": 1
}
}
).fetch();
On the client side (with Minimongo) you'll then need to filter the result further yourself.
There is another way of doing this though. If you run your Mongo query on the server, you won't be using Minimongo, which means projections are supported. As a quick example, try the following:
/server/main.js
const filteredCategories = Categories.find(
{ "items.slug": "mc" },
{
fields: {
"items.$": 1
}
}
).fetch();
console.log(filteredCategories);
The projection will work, and the logged results will match the results you see when using the Mongo console directly. Instead of running your Categories.find on the client side, you could instead create a Meteor Method that calls your Categories.find on the server, and returns the results back to the client.

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") }

MongoDB - Updated $ref value unable to query new value

I've posted the following question which has been answered correctly:
MongoDB - Updating only $ref from DBRef field type
Despite of this when I execute the find method like this:
{ "codeId" : { "$ref" : "code" , "$id" : { "$oid" :
"4ff1c08c6ef25616ce21c4b6"}} }
The document isn't returned... Any idea why?
After the update the document is stored like this:
{ "_id" : { "$oid" : "5097ae1cd3159eb52d05574c"} , "codeId" : { "$ref"
: "code" , "$id" : { "$oid" : "4ff1c08c6ef25616ce21c4b6"}} }
By the way, using uMongo GUI, if I select the Update option over this stored document, and save it, without making any changes whatsoever, and then make the find query once again, the document is returned by the query...
Thanks
This is a clearly one of those DBRef "tweaky" things...
As a temporary (but probably correct) fix, I managed to solve this problem executing this javascript procedure:
var cursor = db.menu.find( { "codeId.$ref" : "version" } );
while( cursor.hasNext() )
{
var document = cursor.next();
db.menu.update(
document,
{ $set: {"codeId" : DBRef("code", document.codeId.$id) }},
{ upsert: false, multi: true }
);
}
Still, I won't consider this to be the best way to achieve what I want... Any other solution that involves less lines?

Categories