我想从java执行复杂的mongodb查询。我有四个字段userid
,statusid
,dateTO
和dateFrom
。复杂查询类似于(userid Or statusid) And (dateFrom < date < dateTo)
。我现在有了查询unitl:
DBObject query = new BasicDBObject();
ArrayList orList = new ArrayList();
ArrayList andList = new ArrayList();
orList.add(new BasicDBObject("user.id", id));
orList.add(new BasicDBObject("retweeted_status.user.id", id));
andList.add(new BasicDBObject("date_posted", new BasicDBObject("$gt", dateFrom)));
andList.add(new BasicDBObject("date_posted", new BasicDBObject("$lt", dataTo)));
orList.add(new BasicDBObject("$and", andList));
query = new BasicDBObject("$or", orList);
如何更改它以执行所需的查询?例如,当我尝试向robomongo发出查询时,它看起来像:
db.coll.find({$and:[{ $or: [ {"user.id":414848505}, {"retweeted_status.user.id":414848505}] },{$and:[{"date_posted":{"$gt":1398948442000}},{"date_posted":{"$lt":1400111999000}}] } ]})
答案 0 :(得分:2)
这是您想要的查询吗?
{
"$and": [
{
"$or": [
{
"user.id" : <id>
},
{
"retweeted_status.user.id": <id>
}
]
},
{
"$and": [
{
"date_posted": {
"$gt": <dateFrom>
}
},
{
"date_posted": {
"$lt": <dateFrom>
}
}
]
}
]
}
如果是,请尝试以下操作:
final DBObject userId = new BasicDBObject("user.id", id);
final DBObject retweetedStatusUserId = new BasicDBObject("retweeted_status.user.id", id);
final DBObject or = new BasicDBObject("$or", Arrays.asList(userId, retweetedStatusUserId));
final DBObject greaterThan = new BasicDBObject("$gt", dateFrom);
final DBObject datePostedGreaterThan = new BasicDBObject("date_posted", greaterThan);
final DBObject lessThan = new BasicDBObject("$lt", dateTo);
final DBObject datePostedLessThan = new BasicDBObject("date_posted", lessThan);
final DBObject and = new BasicDBObject("$and", Arrays.asList(datePostedGreaterThan, datePostedLessThan));
final DBObject query = new BasicDBObject("$and", Arrays.asList(or, and));
答案 1 :(得分:0)
inside class;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
@Autowired(required = true)
private MongoTemplate mongoTemplate;
// inside some method
List<className> list=null;
Query query=new Query();
query.addCriteria(Criteria.where("date_posted").gt(dateFrom);//data type important for passing data
query.addCriteria(Criteria.where("date_posted").lt(dateTo);//data type important for passing data
query.addCriteria(Criteria.where("retweeted_status.user.id").orOperator(Criteria.where("retweeted_status.user.id")).is(id)); //data type important for passing data// example:Integer.valueOf(id);
list=mongoTemplate.find(query, className.class);//put your document class name