MongoDB java 3.2版本查询指定列和排序的补充(待解决:对内嵌集合内的元素进行排序)

因为需要最近使用了mongoDB,上官网一看现在都mongo-java-driver-3.2.2.jar了(以前接触2.X).

于是下载了最新版驱动来用(DB版本:db version v2.4.9),因为新,资料少所以也遇到一些问题,以下就分享出来:

  1. 官方文档里面的东西已经很全面了.常操作一看就明白,就不多说了,可通过以下链接自行查看:https://docs.mongodb.org/getting-started/java/query/
  2. 如果查询指定列应该怎么写呢?X度了一大圈大都是2.几的写法,无奈只能慢慢查API了,参考:http://api.mongodb.org/java/current/com/mongodb/client/FindIterable.html

projection(Bson projection)

Sets a document describing the fields to return for all matching documents.

完整的方法:

// 读取出来保存到别一个集合
		 MongoClient mongoClient = new MongoClient( "localhost" ,27017 );
		 MongoDatabase  database =  mongoClient.getDatabase("test");
		 MongoCollection<Document> collection = database.getCollection("geoptima");
		 Document temp = new Document();
		 temp.put("_id",0);
		 temp.put("geoptima.subscriber",1);
		 System.out.println(  temp.toJson()   );
		 //查询指定列的数据 projection
		 FindIterable<Document> docs =  collection.find(
				 ).sort(new Document("geoptima.subscriber.start",-1) ).projection(temp).limit(5);
		 MongoCursor<Document>  cursor = 	docs.iterator();
		 int i =1;
		 while(cursor.hasNext()){
			 Document doc = cursor.next();
			 System.out.println(i++ +" :   "+doc.toJson());
		 }
		 mongoClient.close();

注意:

temp.put("_id",0): 等于0表示些列不显示

sort项里面的值为-1时:表示降序.>=0时为升序.

以上无法对内嵌集合内的元素进行排序,如有可排序的方法,请留言指导下...

 


来源于:

https://blog.csdn.net/dayuang2009/article/details/50749391

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值