gpt4 book ai didi

java - MongoDB : Converting String Field Into Int using JAVA

转载 作者:行者123 更新时间:2023-11-30 06:13:59 25 4
gpt4 key购买 nike

我正在学习 mongoDB。我有一个看起来像这样的集合:

{
"_id" : ObjectId("558cf353209c021b5a2fcbe5"),
"term" : "gamma red eye tennis dampener",
"year" : "2015",
"month" : "05",
"day" : "29",
"hour" : "09",
"dayofyear" : "176",
"weekofyear" : "26",
"productcount" : "1",
"count" : "1"
}
{
"_id" : ObjectId("578cf353209c021b5a2fcbe5"),
"term" : "tennis dampener",
"year" : "2015",
"month" : "05",
"day" : "29",
"hour" : "09",
"dayofyear" : "176",
"weekofyear" : "26",
"productcount" : "1",
"count" : "7"
}
{
"_id" : ObjectId("568cf353209c021b5a2fcbe5"),
"term" : "gamma ",
"year" : "2015",
"month" : "05",
"day" : "29",
"hour" : "09",
"dayofyear" : "176",
"weekofyear" : "26",
"productcount" : "1",
"count" : "4"
}

这里的字段count 是字符串。我想遍历所有文档并使用 JAVA 将其转换为 INT。

我可以使用这个通过控制台来完成:

db.tq.find().forEach(function(obj) {
obj.count= NumberInt(obj.count);
db.tq.save(obj);
})

如何在 java 中实现?

最佳答案

你应该这样做 -

DBCollection collection = db.getCollection("collection");
BasicDBObject document = new BasicDBObject();
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
DBObject cur = cursor.next();
String id = cur.get("_id").toString();
String c = cur.get("count").toString();
int updateCount = Integer.parseInt(c); //change to int
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set", new BasicDBObject().append("count", updateCount));
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("_id", new ObjectId(id));
collection.update(searchQuery, updateQuery);
}

关于java - MongoDB : Converting String Field Into Int using JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31066829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com