如何在使用mongoDb java异步驱动程序插入mongoDb集合后获取_id
package test;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.allanbank.mongodb.MongoClient;
import com.allanbank.mongodb.MongoClientConfiguration;
import com.allanbank.mongodb.MongoCollection;
import com.allanbank.mongodb.MongoDatabase;
import com.allanbank.mongodb.MongoFactory;
import com.allanbank.mongodb.bson.Document;
import com.allanbank.mongodb.bson.builder.BuilderFactory;
import com.allanbank.mongodb.bson.builder.DocumentBuilder;
import com.allanbank.mongodb.builder.Aggregate;
import com.xxxx.dto.FeedMongoDTO;
/**
* @author abhi
*
*/
public class MongoTestService {
public static transient Log log = LogFactory.getLog(FeedMongoOperations.class);
private MongoClient mongo;
private MongoDatabase db;
private MongoCollection collection;
public boolean openDbConnection() {
try {
MongoClientConfiguration config = new MongoClientConfiguration();
config.addServer("localhost:27017");
config.setMaxConnectionCount(10);
mongo = MongoFactory.createClient(config);
db = mongo.getDatabase("feedDatabase");
return true;
} catch (Exception e) {
return false;
}
}
public boolean closeDbConnection() {
try {
mongo.close();
return true;
} catch (Exception e) {
return false;
}
}
public String save(FeedMongoDTO feed, String collectionName) {
try {
collection = db.getCollection(collectionName);
DocumentBuilder b = BuilderFactory.start();
Document d1 = b.add("url", feed.getUrl()).addLong("mongoTimeStamp", feed.getMongoTimestamp())
.add("feedJsonArray", feed.getFeedJsonArray()).build();
collection.insert(d1);
return d1.get("id").toString();
} catch (Exception ex) {
return null;
}
}
public FeedMongoDTO getFeed(String mongoId, String collectionName) {
FeedMongoDTO feedMongoDTO = null;
try {
return feedMongoDTO;
} catch (Exception ex) {
return null;
}
}
}
FeedMongoDTO
的结构如下所示
public class FeedMongoDTO {
private String id;
private String url;
private Long mongoTimeStamp;
private JSONArray feedJsonArray;
// Getters
public String getId() {
return id;
}
public String getUrl() {
return url;
}
public Long getMongoTimestamp() {
return mongoTimeStamp;
}
public JSONArray getFeedJsonArray() {
return feedJsonArray;
}
// Setters
public void setId(String id) {
this.id = id;
}
public void setUrl(String url) {
this.url = url;
}
public void setMongoTimestamp(Long mongoTimestamp) {
this.mongoTimeStamp = mongoTimestamp;
}
public void setFeedJsonArray(JSONArray feedJsonArray) {
this.feedJsonArray = feedJsonArray;
}
}
我需要获取_id的值,但此处d1.get("id").toString()
导致NullPointerException
还有一件事我很困惑,我是否正确地执行了Save()方法。使用通常的mongodb驱动程序非常容易。
public String save(FeedMongoDTO feed, String collectionName) {
try {
mongoTemplate.save(feed, collectionName);
return feed.getId();
} catch (Exception ex) {
return null;
}
}
提前致谢
Abhilash:)
答案 0 :(得分:3)
如果您需要经常这样做,为什么不自己设置_id。您可以使用0-arg构造函数轻松构造新的ObjectId,并在插入之前将其添加到文档中。
ObjectId id = new ObjectId();
documentBuilder.add("_id", id);
collection.insert(documentBuilder);
似乎很难运行单独的查询只是为了检索id。
答案 1 :(得分:0)
在我看来,异步java驱动程序提供了进行同步查询的方法,例如正常的findOne调用。这对你的需求有意义吗?
答案 2 :(得分:0)
我在使用我的异步节点应用程序在我的目录中创建一个新名称时遇到了这个问题。我想通过它的ID将用户带到新创建的名称,而不会将用户扔回目录列表。 allTwentyQuestions得到了这样的权利,虽然不太适合Node,并引导我走上这条道路:
addName: function(nameDB, newName, callback){
nameID = new require('mongodb').ObjectID();
nameDB.collection('nameList').insert({"_id" : nameID, 'Name' : newName, 'type' : '', 'active' : 'no', 'modifiedDate' : ''}, function(err, result) {
if (!err) {
// success
callback(null, nameID);
} else {
// error
callback('error', err);
}
});
}
然后我会从我的应用程序中调用该函数:
mongo.addName(nameDB, newName, function(err, result) {
if (!err){
// success
// direct the user to the proper page with this new ObjectID found in the var 'result'
} else {
// error
console.log('There was an error adding the name: '+ result);
}
});