- distinct
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
db.person.distinct("fruits.fruitId")
他成功执行了。输出如:
[ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
我想统计集合中共有多少个人[按名字吧]
db.person.distinct("manName")
我想统计指定个数的人的共同关注的朋友。
db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
输出如:
[ "234567", "345678", "456789", "987654", "ni", "wo" ]
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
<context:property-placeholder location="classpath:mongo.properties" />
<!-- Default bean name is 'mongo' -->
<mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
<mongo:db-factory id="mongoDbFactory"
mongo-ref="mongo"
dbname="mongotest" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
</beans>
