如何使用 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;
}
}
提前致谢
阿比拉什 :)