0

我在使用 mongodb + 他们的 java 驱动程序时遇到了一个奇怪的事件。当我进行分组查询时,键的数据类型从 int 变为 double。

(即,我正在对“小时”的键进行分组,该键在所有对象中存储为 int,但在我返回的结果中键更改为 double 类型)。

这不是一个大问题……但奇怪的是它会随意更改这样的键值对的数据类型。有没有其他人出现过这个?这是正常行为吗?

谢谢,

ps 执行常规 .find() 查询会返回正确的数据类型,仅供参考。

编辑:一些示例代码:

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.QueryOperators;

public class MongoTestQueries {

private static final String TESTDBNAME = "badgerbadgerbadger";
private static final String TESTCOLNAME = "mushroom";
private static final Long TESTMAX = 50L;

private static final String KEY1 = "a";
private static final String KEY2 = "snake";
private static final String KEY3 = "plane";

/**
 * This starts running it.
 * 
 * @param args
 *            the arguments.
 */
public static void main(final String[] args) {
//You'll need to write your own code here for connecting to db as you see fit.
    MongoConnection mc = new MongoConnection("someserver.com", TESTDBNAME);
    mc.setCurCol(TESTCOLNAME);
    mc.getCurCol().drop();
    mc.setCurCol(TESTCOLNAME);


    DBCollection col = mc.getCurCol();

    populateCollection(col);
    System.out.println(col.count() + " inserted into db.");

    regGroupSearch(col);

}

private static void populateCollection(DBCollection col) {
    for (Long l = 0L; l < TESTMAX; l++) {
        col.insert(new BasicDBObject(KEY1, new Integer(l.intValue())).append(KEY2,
                Math.random()).append(KEY3, (TESTMAX - l) + "a string"));
    }
}

private static void regGroupSearch(final DBCollection col) {
    System.out.println("Group Search:");
    DBObject key = new BasicDBObject(KEY1, true).append(KEY3, true);
    DBObject cond = new BasicDBObject().append(KEY1, new BasicDBObject(QueryOperators.GT, 4.0));
    DBObject initial = new BasicDBObject("count", 0).append("sum", 0);
    String reduce = "function(obj,prev){prev.sum+=obj." + KEY2 + ",prev.count+=1}";
    String finalize = "function(obj){obj.ave = obj.sum/obj.count}";
    DBObject groupResult = col.group(key, cond, initial, reduce, finalize);
    printDBObject(groupResult);
    System.out.println("Done.");
}

private static void printDBObject(final DBObject toPrint) {
    for (String k : toPrint.keySet()) {
        System.out.println(k + ": " + toPrint.get(k));
    }
}

}

4

0 回答 0