EzDevInfo.com

jongo

Query in Java as in Mongo shell Jongo {mongo-java-driver: 'with ease'} query in java as in mongo shell (using strings), unmarshall results into java objects (using jackson)

What does the @Id annotation?

I have a class that has this note, @Id, what is the use of it?

package oknok.validacao.resources;

import org.jongo.marshall.jackson.oid.Id;

public class Validacao {

    @Id
    String id;
    String email;
    String instancia;
    String dataCriacao;
    String dataAtualizacao;

}

Source: (StackOverflow)

(MongoDB Java) $push into array

Good morning, I'm using mongo 2.2.3 and the java driver. My dilemma, I have to $push a field and value into an array, but I cant seem to figure out how to do this. A sample of my data:

"_id" : 1,
"scores" : [
    {
        "type" : "homework",
        "score" : 78.97979
    },
    {
        "type" : "homework",
        "score" : 6.99
    },
    {
        "type" : "quiz",
        "score" : 99
    }
]

I can $push in the shell:

db.collection.update({_id:1},{$push:{scores:{type:"quiz", score:99}}})

but it's when I translate this into java I confuse my self and chuck my keyboard at a wall.

my java code (incomplete and wrong) so far:

DBObject find = new BasicDBObject("_id", 1);
DBObject push = new BasicDBObject("$push", new BasicDBObject(
                        "scores", new BasicDBObject()));

Any help is greatly appreciated.


Source: (StackOverflow)

Advertisements

Is there a simple way to map a Bson array to Java ArrayList with mongo and jongo?

I'm new to mongodb and I am using jongo.

I am trying to map a Bson array to Java ArrayList.

Is there a simple way to do that?

my pojo-

public class Member {

@Id
String _id;
String username;
String password;
String email;

ArrayList<String> friends;

public Member() {
    friends = new ArrayList<String>();
}

public Member(String username, String password, String email) {
    this.username = username;
    this.password = password;
    this.email    = email;
    friends       = new ArrayList<String>();
}

some methods    
...
}

My Bson object looks like -

{username: 'Joe',password: '123456' ,email: 'Joe@example.com', friends : ['Adam','Ben', 'Josh']}

Trying to build an ArrayList from "friends".

The array list I get from jongo contains nothing


Source: (StackOverflow)

Jongo vs (DBObject)JSON.parse

I'm trying to figure out the advantage of Jongo over simply unmarshalling the json command using (DBObject)JSON.parse(...) and using the DBObject in the below fashion.

Is there a performance advantage?

    @Override
public List<T> getEntityList(Integer limit, String query) throws Exception {
    log.entering(DaoImpl.class.toString(), "getEntityList, with criteria of " + query);
    DBObject criteriaObject = null;
    ArrayList<T> list = new ArrayList<T>();

    if (query != null)
        criteriaObject = (DBObject)JSON.parse(query);

    DBCursor cursor = null;

    try {
        if (criteriaObject != null) {
            log.log(Level.FINEST, "getting the objects using a search criteria: " + criteriaObject);
            cursor = MongoDB.getInstance().getCollection(collection).find(criteriaObject);
        } else {
            log.log(Level.FINEST, "getting the objects without a criteria");
            cursor = MongoDB.getInstance().getCollection(collection).find();
        }

        ............etc, etc, etc

Thanks!


Source: (StackOverflow)

Querying for date using jongo driver for mongo

I use jongo driver to connect to my mongoDB .

The syntax for querying - for ex, some age less than 18 - is

collection.find("{age: {$lt : 18}}");

but how to query for a date ?

In the mongoDB the date key value pair is stored like

{"date" : ISODate("2012-11-23T00:12:23.123Z")}

so I tried the following:

collection.find("{date: {$lt : ISODate(\"2012-11-23T00:13:00.000Z\")}}");

but I get this exception while running the java code :

Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.IllegalArgumentException: {dateLastSeen: {$lt: ISODate("2012-11-23T00:13:00.000Z")}} cannot be parsed
        at org.jongo.query.Query.convertToDBObject(Query.java:33)
        at org.jongo.query.Query.<init>(Query.java:26)
        at org.jongo.query.QueryFactory.createQuery(QueryFactory.java:38)
        at org.jongo.Find.<init>(Find.java:42)
        ... 10 more
Caused by: com.mongodb.util.JSONParseException:
{dateLastSeen: {$lt: ISODate("2012-11-23T00:13:00.000Z")}}
                     ^
        at com.mongodb.util.JSONParser.parse(JSON.java:198)
        at com.mongodb.util.JSONParser.parseObject(JSON.java:231)
        at com.mongodb.util.JSONParser.parse(JSON.java:195)
        at com.mongodb.util.JSONParser.parseObject(JSON.java:231)
        at com.mongodb.util.JSONParser.parse(JSON.java:195)
        at com.mongodb.util.JSONParser.parse(JSON.java:145)
        at com.mongodb.util.JSON.parse(JSON.java:81)
        at com.mongodb.util.JSON.parse(JSON.java:66)
        at org.jongo.query.Query.convertToDBObject(Query.java:31)

So I think, that dates are not to be plainly converted to the corresponding string, but the syntax to search using date is different.

Anybody with jongo knowledge who can help ?


Source: (StackOverflow)

Mongo Java drivers & mappers performances

Mongo in Java can be used with several tools:

Is there some benchmarks comparing mappers to drivers performances and one versus each others?


Source: (StackOverflow)

In Jongo, how to find multiple documents from Mongodb by a list of IDs

In mongodb, I can do this by the following query:

find(
    { _id : { $in : [ ObjectId('5275c6721a88939923c3ea54'), ObjectId('5275c6721a88939923c3ea55'), ObjectId('5275c6721a88939923c3ea56'), ObjectId('5275c6721a88939923c3ea57'), ObjectId('5275c6721a88939923c3ea58') ] } }
)

But how can we do the same using Jongo code?

I know we can find one document via:

db.getCollection("mongoEg").findOne(Oid.withOid("5194d46bdda2de09c656b64b")).as(MongoTest.class);

But how to get more than one documents in one query via Jongo?


Source: (StackOverflow)

Mongodb / Jongo sorting then limit, vs, limit then sorting

Are these two guaranteed to be the same:

collection.limit(10).sort("{score: -1}")

vs

collection.sort("{score: -1}").limit(10)

The second one does a global sort, and returns the top 10. Is the first one guaranteed to do the same, or may it just return 10 sorted records?

Thanks


Source: (StackOverflow)

Does list operations load whole data at first call?

Suppose I've got very big collection and I select it by

MongoCursor<MyClass> answer = myCollection.find().as(MyClass.class);  

Will Jongo/Mongo load whole collection at the first call or incrementally load data while I will iterate over answer?


Source: (StackOverflow)

How to get jar lib files of jongo?

Follow at jongo a java library on top of MongoDB allow Query in Java as in Mongo shell. Example:

SHELL

db.friends.find({"age": {$gt: 18}});

JAVA DRIVER

friends.find(new BasicDBObject("age",new BasicDBObject("$gt", 18)));

JONGO

friends.find("{age: {$gt: 18}}").as(Friend.class);

But i can't find anything to download this jar lib files. Who could share this file for me?

Thanks in advanced.


Source: (StackOverflow)

Rename ObjectId _id to id in jackson deserialization with Jongo and MongoDB

I've just started working on a project using the play framework,jongo and MongoDB. The project was initially written in Play 2.1 with pojos with an String id field annotated with both: @Id and @ObjectId This would persist to Mongo as an ObjectId and when deserialized would output the id as: "id":"53fcb9ede4b0b18314098d10" for example.

Since upgrading to Jongo 1.1 and Play 2.3.3 the id attribute is always named "_id" when deserialized, I want the attribute to retain the field name yet I can't use @JsonProperty("custom_name") as the Jongo @Id annotation does @JsonProperty("_id") behind the scenes.

import org.jongo.marshall.jackson.oid.Id;
import org.jongo.marshall.jackson.oid.ObjectId;

public class PretendPojo {

    @Id
    @ObjectId
    private String id;

    private String name;

    public PretendPojo() {
    }

    public PretendPojo(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

The POJOs when persisted in MongoDB look like this if I view them via RoboMongo

{
    "_id" : ObjectId("53fc984de4b0c34f1905b8ee"),
    "name" : "Owen"
}

However when I deserialize them I get the following json if I keep both annotations:

{"name":"Owen","_id":{"time":1409072858000,"date":1409072858000,"timestamp":1409072858,"new":false,"timeSecond":1409072858,"inc":308487737,"machine":-458223042}}

and the following output if I only use the @Id annotation.

{"name":"Owen","_id":"53fcbedae4b0123e12632639"}

I have a test case for working with the PretendPojo show above:

   @Test
    public void testJongoIdDeserialization() throws UnknownHostException {
        DB database = new MongoClient("localhost", 27017).getDB("jongo");
        Jongo jongo = new Jongo(database);
        MongoCollection collection = jongo.getCollection("jongo");
        collection.save(new PretendPojo("Owen"));
        PretendPojo pretendPojo = collection.findOne("{name:   \"Owen\"}").as(PretendPojo.class);
        JsonNode json = Json.toJson(pretendPojo);
        assertNotNull(json.get("id"));
    }

When trying to use custom deserializers I never can get hold of the object ID I seem to only have access to the date/time/timestamp data that is currently being deserialized.

Ideally the output I'm looking for would be:

  {"name":"Owen","id":"53fcbedae4b0123e12632639"}

Any help will be greatly appreciated! :)


Source: (StackOverflow)

Query entire collection in jongo

I'm trying to get all results from this collection and them trying to print the first one:

MongoCollection musics = JNDIManager.getJongoCollection("musics");
Iterable<MusicObject> all = musics.find().as(MusicObject.class);

where MusicObject class:

public class MusicObject {
    @Id
    private final String _id; // refers to directory
    private String name;
    private String directory;

    MusicObject() {};
}

and db.musics.find() results in

{"_id": ObjectId("..."), "name": " Certain Name", "directory" : "C:\\..."}
{"_id": ObjectId("..."), "name": " Certain Name 2", "directory" : "C:\\..."}
{"_id": ObjectId("..."), "name": " Certain Name 3", "directory" : "C:\\..."}

with the full exception stack trace

org.jongo.marshall.MarshallingException: Unable to unmarshall result to class br.com.evans.dao.musics.MusicObject from content {"_id": ObjectId("..."), "name": " Certain Name", "directory" : "C:\\..."}
at org.jongo.marshall.jackson.JacksonEngine.unmarshall(JacksonEngine.java:45)
at org.jongo.ResultHandlerFactory$ResultUnmarshallingHandler.map(ResultHandlerFactory.java:43)
at org.jongo.MongoIterator.next(MongoIterator.java:44)
at br.com.evans.jdni.music.MusicPlayer.setMusicListFromDB(MusicPlayer.java:52)
at br.com.evans.command.repository.CommandRepository.proccesNode(CommandRepository.java:47)
at br.com.evans.behavior.nodes.core.MusicBehavior.execute(MusicBehavior.java:40)
at br.com.evans.servlets.behavior.BehaviorExecution.doPost(BehaviorExecution.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at br.com.evans.servlet.filters.SessionFilter.doFilter(SessionFilter.java:55)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.io.CharConversionException: Invalid UTF-32 character 0x64695f07(above 10ffff)  at char #1, byte #7)
at com.fasterxml.jackson.core.io.UTF32Reader.reportInvalid(UTF32Reader.java:155)
at com.fasterxml.jackson.core.io.UTF32Reader.read(UTF32Reader.java:109)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.loadMore(ReaderBasedJsonParser.java:122)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._skipWSOrEnd(ReaderBasedJsonParser.java:1651)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:552)
at com.fasterxml.jackson.databind.ObjectReader._initForReading(ObjectReader.java:1293)
at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1199)
at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:862)
at org.jongo.marshall.jackson.JacksonEngine.unmarshall(JacksonEngine.java:42)
... 27 more

How to fix this? I've searched the jongo documentation and I can understand that I'm mapping my MusicObject wrong, just don't know what am I supposed to do. Tried @Id, long, String, @ObjectId

Edit: Also, dropped the unique index that was in directory column.


Source: (StackOverflow)

What is the different between MongoDB plugins for Play framework2?

I'm starting to learn MongoDB, integrated with Play framework 2. I goggled about how to integrate it with Play framework2 and finally found many plugins available:

I'm quite confused which one should be used in order to organize my MongoDB. I was trying to search about how different between them, however, cannot find any document. So, If anyone has some experience about them, could you please share you opinion or explain the most different between them?


Source: (StackOverflow)

Jongo Maven Dependency causing problems

I am currently trying to use the Jongo project to connect to a remote MongoDB. To do so, I added these dependencies to my project :

<dependencies>
    <dependency>
        <groupId>org.jongo</groupId>
        <artifactId>jongo</artifactId>
        <version>1.0</version>
    </dependency>

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>2.6.5</version>
    </dependency>
</dependencies>

I already had some troubles with the first dependency (jongo:1.0), since maven could not retreive this version (the latest maven knew was 0.4) : Intellij tells me Dependency "org.jongo:jongo:1.0" not found. Yet, the dependency can be found there

I managed to get it via Project Structure -> Librairies

enter image description here

The problem is that this dependency is now local, and anyone who clones this project must import this dependency manually, which is not suitable.

I am using Intellij IDEA 13.0


Source: (StackOverflow)

Creating a dynamic query with MongoDB, Java and Jongo

I'm using a combination of Java, the Play Framework using Java and not Scala, MongoDB and Jongo as my go between for a basic web CRUD app. I keep receiving a JSON parse exception even though my string doesn't contain any illegal characters. It's actually failing on closing curly bracket at the end of the statement. Below is my error and code. The query string is just a string builder, searching if an object is empty or has a value, if it has a value it's appended to a string.

Jongo method:

public static Iterable<OneDomain> findWithQueryString(String queryString){
    return domains().find("{#}", queryString).as(OneDomain.class);
}

Controller Methods: String builder example:

        if(queryStringBuilder.toString().equalsIgnoreCase("")){
            queryStringBuilder.append("date: {$gte : " + searchObj.dateFrom + ", $lt: " + searchObj.dateTo + "}");
        }else{
            queryStringBuilder.append(" , ");
            queryStringBuilder.append("date: {$gte : " + searchObj.dateFrom + ", $lt: " + searchObj.dateTo + "}");
        }

        String queryString = queryStringBuilder.toString();

        Iterable<OneDomain> filteredIterable = OneDomain.findWithQueryString(queryString);

Gives me this error:

   Caused by: com.mongodb.util.JSONParseException:
   {"source : Online Lists , blacklist : true , vetted : true , is : false , isNot : true"}
                                                                                          ^

with the error on the "}" ending it.

In addition to that, if I try to escape the characters by putting in a \" so it becomes \"date\" it will parse and error out like so:

   Caused by: com.mongodb.util.JSONParseException:
   {"\"source\" : \"Online Lists\" , \"blacklist\" : true , \"vetted\" : true , \"is\" : false , \"isNot\" : true"}

Can I actually do this or because it's Java being inserted into it, the quotes will be around the whole string and thus it's trying to read it as a single JSON field vs it being the whole query?


Source: (StackOverflow)