Simple select from MongoDB with vibed - mongodb

I am learning how to use MongoDB from vibed. I wrote simple app, that as I am thinking should do find operation. But when I run it I am getting error: Querying uninitialized MongoCollection.. What I am doing wrong?
import vibe.core.log;
import vibe.db.mongo.mongo;
import vibe.d;
import std.stdio;
import std.array;
void main()
{
MongoCollection m_posts;
foreach(p;m_posts.find("{}"))
{
writeln(p);
}
}

There is a mongo example in vibe.d repository.
It comes down to this pattern:
void main()
{
auto db = connectMongoDB("localhost").getDatabase("test");
auto coll = db["collection"];
foreach (i, doc; coll.find("{}"))
writeln("Item %d: %s", i, doc.toJson().toString());
}
In your snippet you have attempted to use collection object without actually connecting to the database and retrieving it from there. This is exactly what error is about.

You just created the MongoCollection object and did not initialized it with anything. That's why the error is about an "Uninitialized Collection". You should connect it to a database and put some data in it. Have a look at http://vibed.org/api/vibe.db.mongo.collection/MongoCollection for examples.

Related

"TypeError: this.types is not a function" when using "vuex-orm-decorators"

I'm trying to use the npm package 'vuex-orm-decorators' from https://github.com/scotley/vuex-orm-decorators#readme
When I try to insert into the DB, I get the error TypeError: this.types is not a function
Entity looks like this
import { Model } from "#vuex-orm/core";
import { NumberField, OrmModel, StringField } from "vuex-orm-decorators";
#OrmModel("races")
export default class Race extends Model {
#NumberField()
public ID!: number;
#StringField()
public Name!: string;
}
store looks like this:
import Vue from "vue";
import Vuex from "vuex";
import { ORMDatabase } from "vuex-orm-decorators";
Vue.use(Vuex);
export default new Vuex.Store({
.
.
.
plugins: [ORMDatabase.install()]
});
Also, maybe this is a clue.... in Vuex-Orm, this.setters is returning a value, but this.setters('all') is returning undefined.
/**
* Get all records.
*/
Model.all = function () {
return this.getters('all')();
};
From seeing the undefined basic fields and functions, it seems like the vuex-orm database isn't getting set up correctly. Any ideas?
I tried to create a stackoverflow tag for vuex-orm-decorators, but I'm not quite at 1500 rep yet, so I just tagged it as vuex-orm.
There is a small bug in vuex-orm-decorators package in the implementation of the types function defined in Vuex-ORM Single Table Inheritance docs.
I've created a fork in which I fixed this simple problem and created a pull request to update the original package.
Lastly, I've to point that from my tiny dive into this package that it isn't fully ready yet for table inheritance features built in Vuex-ORM but still is great for simple use cases.

How to use parameter passed from JSP to servlet and include it in find query in MongoDB

I have passed a parameter from a JSP to servlet. How do I include this in the find() query to search for that result in MongoDB?
Assuming that you have resolved all JSP/servlet stuff, take a look to this tutorial about Java Mongo Driver where you can find how to do that and other basics things.
Following this tutorial you can define filters in your query as follows:
package com.mongoclient.MongoHelloWorld;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import static com.mongodb.client.model.Filters.eq;
public class MongoHelloWorldApplication {
public static void main(String[] args) {
// Create Mongo connection to the DB
MongoClient mongoClient = new MongoClient( "localhost", 27017);
// Select the DB
MongoDatabase database = mongoClient.getDatabase("myDatabase");
// Select the collection
MongoCollection<Document> collection = database.getCollection("myCollection");
// Make the query
Document myDoc = collection.find(eq("myField", "myValue")).first();
// Print result
System.out.println(myDoc.toJson());
}
}
In the previous example I use eq for equality comparison but you have java class like gt or lt for inequality comparison, and, or and so on... You could check the doc for more examples.
Regards!

List all tables in an mdb file

Is there any way to list the names of all of the tables in an MDB file? I am attempting to create a program that tests the user on Quizbowl questions. I would like to organize the questions and answers so that each question set is located within its own table. Simply put, I am unfamiliar with the API for Jackcess - I have tried searching to see if there is a method that would do this, but have failed.
Thank you.
Simply use the .getTableNames() method of the Database object, like this:
import java.io.File;
import com.healthmarketscience.jackcess.Database;
// ...
String dbFileSpec = "C:/Users/Public/mdbTest.mdb";
try (Database db = DatabaseBuilder.open(new File(dbFileSpec))) {
for (String tableName : db.getTableNames()) {
System.out.println(tableName);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}

How to query mongodb from groovy/grails?

Do I have to have a domain object to query mongodb?
What if I just want some raw data to be displayed? What would be the syntax to query mongodb from my controller?
I tried
"def var = db.nameOfMyCollection.find()"
but it says no such property as db in my controller class.
I know that my application is connecting to the database because I am monitoring mongo server log and it increases the number of connections by one when I launch my grails app.
Assuming you have added mongodb java driver dependency in build config and refreshed your dependencies.
Create a grails service named MongoService.groovy and put the following code.
Dont forget to import mongodb
package com.organisation.project
import com.mongodb.*
class MongoService {
private static MongoClient mongoClient
private static host = "localhost" //your host name
private static port = 27017 //your port no.
private static databaseName = "your-mongo-db-name"
public static MongoClient client() {
if(mongoClient == null){
return new MongoClient(host,port)
}else {
return mongoClient
}
}
public DBCollection collection(collectionName) {
DB db = client().getDB(databaseName)
return db.getCollection(collectionName)
}
}
We can now use this MongoService in our controllers or other services.
Now you can do following stuff in your controller.
Dont forget to import mongodb.DBCursor
package com.organisation.project
import com.mongodb.DBCursor
class YourControllerOrService {
def mongoService //including Mongo service
def method(){
def collection = mongoService.collection("your-collection-name")
DBCursor cursor = collection.find()
try{
while(cursor.hasNext()){
def doc = cursor.next()
println doc //will print raw data if its in your database for that collection
}
}finally {
cursor.close()
}
}
}
For more info Refer mongodb java docs
Ok, solved.
This is how you go about accessing the database.
import com.mongodb.*
MongoClient mongoClient = new MongoClient("localhost", 27017)
DB db = mongoClient.getDB("db");
I actually solved it using Java and then pasted it into groovy and it works there as well which shouldn't come as a surprise. The difference is that in Java you actually have to import the jar driver, but in Grails, you install the Mongo GORM plugin.
Assuming you are using the MongoDB GORM Plugin, if you have domain classes in your grails application, you can use them as you would with any relational db backend.
However, per this documentation, you can access the low-level Mongo API in any controller or service by first declaring a property mongo, just as you would a service, then getting the database you are targeting:
def mongo
def myAction = {
def db = mongo.getDB("mongo")
db.languages.insert([name: 'Groovy'])
}

How to retrieve dynamic content from database?

I'm evaluating java-based cms and selecting one as our cms ,now I'm learning dotcms , I need to know how to retrieve content from db like traditional jsp/bo does,I'm new to dotcms, the official documents only tell how to add static content but dynamic content , say running a sql and getting the wanted data ,then putting them into pages. We are doing an internal website where employees can browse news, events, colleagues information etc which managed through a cms, the information is definitely dynamic and updated regularly. We plan to use spring mvc on the project. Any ideas on the question?
thank you.
To get this to work you need to do a few things:
If you want to use a different database, then you can add a new resource to the conf/Catalina/localhost/ROOT.xml file. If you want to use the dotCMS database to host the additional tables then you can skip this step.
From within your java code you can get a database connection using the DbConnectionFactory class. Now you can read the data from the database. Here's an example:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Connection conn = DbConnectionFactory.getConnection();
Statement selectStatement;
try {
selectStatement = conn.createStatement();
try {
selectStatement.execute("SELECT * FROM your_table WHERE your_where_clause etc...");
ResultSet result = selectStatement.getResultSet();
if (result.next()) {
.. do your stuff here...
// for example:
// Long dbId = result.getLong("Id");
// String stringField = result.getString("stringFieldName");
// int intField = result.getInt("intFieldName");
} finally {
selectStatement.close();
}
} catch (SQLException e1) {
// Log the error here
}
}
If you want to use this data in velocity you'll need to create a viewtool. Read more about that here: http://dotcms.com/docs/latest/DynamicPluginsViewtool