我試圖在我的資料中獲取“坐標”型別的所有值(它們是陣列),如下所示:
[
["51.50064317423898","-0.09372711181640626"],
["51.48465408363687","-0.13149261474609378"]
]
我試過 db.collections("mydb").distinct("coordinate") 但我得到:
[
'-0.09372711181640626',
'-0.13149261474609378',
'51.48465408363687',
'51.50064317423898'
]
有誰知道我如何可以像我想要的那樣擁有我的所有陣列而不是在一個陣列中排序?“mydb”看起來像這樣:
{
"name":"dfbfdbf",
"coordinate":["51.50064317423898","-0.09372711181640626"],
"rating":"8",
"description":"geojzglijsen"
},
{
"name":"qzfgs",
"coordinate":["51.48465408363687","-0.13149261474609378"],
"rating":"5",
"description":"femkndsmnk"
}
謝謝!
uj5u.com熱心網友回復:
如果我理解正確,你可以試試這個聚合查詢:
問題的關鍵是$group通過null讓所有值和使用$addToSet,防止重復的值。
db.collection.aggregate([
{
"$group": {
"_id": null,
"coordinate": {
"$addToSet": "$coordinate"
}
}
},
{
"$project": {
"_id": 0
}
}
])
此處的示例,我復制了一個物件以查看不顯示重復值的方式。
uj5u.com熱心網友回復:
如果您需要從您的收藏中獲取不同的坐標:
mongos> db.a.find()
{ "_id" : ObjectId("619ea12e032deead586f3f91"), "name" : "dfbfdbf", "coordinate" : [ "51.50064317423898", "-0.09372711181640626" ] }
{ "_id" : ObjectId("619ea138032deead586f3f92"), "name" : "a", "coordinate" : [ "51.50064317423898", "-0.09372711181640626" ] }
{ "_id" : ObjectId("619ea14c032deead586f3f93"), "name" : "a", "coordinate" : [ "51.50064317423898", "-0.19372711181640626" ] }
{ "_id" : ObjectId("619ea157032deead586f3f94"), "name" : "a", "coordinate" : [ "51.50064317423898", "-0.09372711181640626" ] }
{ "_id" : ObjectId("619ea15b032deead586f3f95"), "name" : "a", "coordinate" : [ "52.50064317423898", "-0.09372711181640626" ] }
{ "_id" : ObjectId("619ea160032deead586f3f96"), "name" : "a", "coordinate" : [ "52.50064317423898", "-0.09372711181640626" ] }
mongos> db.a.aggregate([
{ $addFields:{coordinates:{$reduce:{ input: {$slice:["$coordinate",1,{$size:"$coordinate"} ]},initialValue:{$arrayElemAt:["$coordinate",0]},in:{$concat:["$$value",";","$$this" ]} }} }} ,
{ $group:{_id:"$coordinates" , cnt:{$sum:1}}} ,
{ $project : { coordinate : { $split: ["$_id", ";"] } ,_id:0}}
])
{ "coordinate" : [ "51.50064317423898", "-0.19372711181640626" ] }
{ "coordinate" : [ "51.50064317423898", "-0.09372711181640626" ] }
{ "coordinate" : [ "52.50064317423898", "-0.09372711181640626" ] }
mongos>
例子: 這里
解釋:從集合中洗掉重復的坐標
- 創建新的欄位坐標,您可以在其中加入單個字串中的坐標
- 對坐標進行分組以洗掉重復項
- 將坐標拆分為原始值。
該解決方案也沒有 16MB 的不同坐標陣列摘要大小的限制......
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366833.html
