6
 private void getUsersWithin24Hours(String id, Map < String, Object > payload) throws JSONException {
  JSONObject json = new JSONObject(String.valueOf(payload.get("data")));
  Query query = new Query();

  query.addCriteria(Criteria.where("user_id").is(id).and("timezone").in(json.get("timezone")).and("gender").in(json.get("gender")).and("locale").in(json.get("language")).and("time").gt(getDate()));
  mongoTemplate.getCollection("user_log").distinct("user_id", query.getQueryObject());
 }

I was going to made a query and get result from mongodb and I was succeed with mongo terminal command:

db.getCollection('user_log').find({"user_id" : "1", "timezone" : {$in: [5,6]}, "gender" : {$in : ["male", "female"]}, "locale" : {$in : ["en_US"]}, "time" : {$gt : new ISODate("2017-01-26T16:57:52.354Z")}}) 

but from java when I was trying it gave me below error.

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class org.json.JSONArray

What is the ideal way to do this?

Hint : actually I think in my code error occurred of this part json.get("timezone"). because it contains array. When I am using hardcode string arrays this code works

3
  • Could you please provide your pom.xml ? Commented Jan 27, 2017 at 14:56
  • @MickaëlB actually it long 1072 lines. Can you tell me what do you want to know Commented Jan 27, 2017 at 14:58
  • Nerver mind. I'll provide a minimal answer to show you how it works. Commented Jan 27, 2017 at 15:00

2 Answers 2

2

You don't have to use JSONObject/JSONArray for conversion.

Replace with below line if the payload.get("data") is Map

BasicDBObject json = new BasicDBObject(payload.get("data"));

Replace with below line if the payload.get("data") holds json string.

BasicDBObject json =(BasicDBObject) JSON.parse(payload.get("data"));
Sign up to request clarification or add additional context in comments.

6 Comments

This looks ok. But I sloved this with pojo class
It depends on your use case. Yo';ll need add a codec if you want to use JSONObject/JSONArray as MongoDB dont have any knowledge of those types.
This is the Query genarate "{ "user_id" : "1" , "timezone" : { "$in" : [ [ "5" , "6" , "5.5"]]} , "gender" : { "$in" : [ [ "male" , "female"]]} , "locale" : { "$in" : [ [ "en_US" , "en_GB"]]} , "time" : { "$gt" : { "$date" : "2017-01-28T11:51:32.869Z"}}}" by 2nd option you gave . because array contain another array query did not work. any idea why?
Yes, but why do have array within array ? Is that your structure ?
no, I want ""timezone" : { "$in" : [ "5" , "6" , "5.5"]}" but code gives me like this "timezone" : { "$in" : [ [ "5" , "6" , "5.5"]]}"
|
1

Here's an example of MongoDB from MongoDB University course with a MongoDB database named "students" with a collection named "grades" :

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mongodb</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>test</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.2.2</version>
        </dependency>
    </dependencies>
</project>

com/mongo/Main.java

package com.mongo;

import com.mongodb.MongoClient;
import com.mongodb.client.*;
import org.bson.Document;
import org.bson.conversions.Bson;

import javax.print.Doc;

public class Main {

    public static void main(String[] args) {

        MongoClient client = new MongoClient();
        MongoDatabase database = client.getDatabase("students");
        final MongoCollection<Document> collection = database.getCollection("grades");

        Bson sort = new Document("student_id", 1).append("score", 1);
        MongoCursor<Document> cursor = collection.find().sort(sort).iterator();

        try {
            Integer student_id = -1;
            while (cursor.hasNext()) {
                Document document = cursor.next();
                // Doing more stuff
            }
        } finally {
            cursor.close();
        }
    }
}

2 Comments

actually I think in my code error occurred of this part json.get("timezone"). because it contains array. When I am using hardcode string arrays this code works
I don't think so. Your exception CodecConfigurationException belongs to org.bson group and not org.json. I think your problem is that json.get("timezone") return JSONArray with is not supported in Criteria unless you have a specific codec. Can you try json.get("timezone").toString() instead ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.