我正在开发Mongodb独特查询,我有一个重复输入的集合,我按照created_at进行操作。但我想在没有重复值的情况下获取。
示例JSON
{
"posts": [{
"id": "580a2eb915a0161010c2a562",
"name": "\"Ah Me Joy\" Porter",
"created_at": "15-10-2016"
}, {
"id": "580a2eb915a0161010c2a562",
"name": "\"Ah Me Joy\" Porter",
"created_at": "25-10-2016"
}, {
"id": "580a2eb915a0161010c2a562",
"name": "\"Ah Me Joy\" Porter",
"created_at": "01-10-2016"
}, {
"id": "580a2eb915a0161010c2bf572",
"name": "Hello All",
"created_at": "05-10-2016"
}]
}
Mongodb查询
db.getCollection('posts').find({"id" : ObjectId("580a2eb915a0161010c2a562")})
所以我想了解mongodb的独特查询,请通过我的帖子告诉我。
答案 0 :(得分:0)
尝试如下:
db.getCollection('posts').distinct("id")
它将返回集合posts
中的所有唯一ID,如下所示:
["580a2eb915a0161010c2a562", "580a2eb915a0161010c2bf572"]
来自MongoDB文档:
该示例使用包含以下文档的inventory
集合:
{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }
返回字段的不同值(dept
):
db.inventory.distinct( "dept" )
该方法返回以下不同dept值的数组:
[ "A", "B" ]
参考:
答案 1 :(得分:0)
根据我的理解,您希望得到截然不同的结果,这样可以消除该集合中的重复id
通过在mongodb中使用distinct,它将返回不同值的列表
db.getCollection('posts').distinct("id");
["580a2eb915a0161010c2a562", "580a2eb915a0161010c2bf572"]
所以你应该研究mongodb聚合
db.posts.aggregate(
{ "$group" : { "_id" : "$id", "name" : {"$first" : "$name"}, "created_at" : {"$first" : "$created_at"} }}
)
输出结果列表将消除重复的id
文档