[英]Query for similar array in MongoDB
我想在我的 MongoDB 集合中搜索具有相似數組的文檔,並按相似值排序。
示例:
我會搜索{chars:['a', 'b', 'c']}
我已經存儲了這些文件:
1. {chars:['s', 'e', 'c']}
2. {chars:['i', 'l', 'd']}
3. {chars:['b', 'a', 'c']}
4. {chars:['f', 'c', 'b']}
我想得到一些訂購的東西:
[
{chars:['b', 'a', 'c'], similarity: 1.0},
{chars:['f', 'c', 'b'], similarity: 0.66},
...
]
我應該使用哪種運算符或查詢策略來獲得類似的結果?
謝謝!
感謝所有試圖幫助我的人。 我感謝您的幫助。
我通過聚合管道找到了解決方案。
var myArray = ['a', 'b', 'c'];
db.test.aggregate([
{
$unwind: '$chars',
},
{
$match: { chars: { $in: myArray } },
},
{
$group: {
_id: '$_id',
count: { $sum: 1 },
},
},
{
$project: {
_id: 1,
count: 1,
score: { $divide: ['$count', myArray.length] },
},
},
{
$sort: { score: -1 },
},
]);
這是控制台返回的內容:
{ "_id" : ObjectId("586ebeacb2ec9fc7fef5ce31"), "count" : 3, "score" : 1 }
{ "_id" : ObjectId("586ebeb9b2ec9fc7fef5ce32"), "count" : 2, "score" : 0.6666666666666666 }
{ "_id" : ObjectId("586ebe89b2ec9fc7fef5ce2f"), "count" : 1, "score" : 0.3333333333333333 }
希望有人覺得這很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.