最佳答案
首先,以对象数组的形式获取数据。然后,我们可以使用以下算法来得到您所需要的:
- 获取独特的类别
[“音乐”、“电影”、“历史”、“科学”]
- 获取这些类别的组合
[[“音乐”,“电影”],[“音乐”,“历史”],[“音乐”,“科学”],[“电影”,“历史” “],...]
- 创建类别名称到该类别中包含的图书的映射。我们可以使用
Set
来确保值是唯一的。该 map 的结构类似于{"Music": Set("A", "B"), "Film": Set("A", "B", "C"), "History": Set (“C”,“B”),“科学”:设置(“C”)}
- 使用您刚刚创建的对象和数组来查找组合之间的重复项。
- 完成所有操作后,您将得到一个具有以下结构的数组:
[ [cat1, cat2, [bookInCommon1, bookInCommon2]], [cat1, cat3, [bookInCommon1, bookInCommon2]], ...]
运行下面的代码以查看其实际效果。 mongoData
保存从 Mongo 获取的数据。
const mongoData = [{
category: "Music",
book: "A"
}, {
category: "Music",
book: "B"
},{
category: "Music",
book: "A"
},{
category: "Film",
book: "A"
},{
category: "Film",
book: "A"
},{
category: "Film",
book: "B"
},{
category: "Film",
book: "C"
},{
category: "Film",
book: "C"
},{
category: "Film",
book: "A"
},{
category: "History",
book: "C"
},{
category: "History",
book: "C"
},{
category: "History",
book: "B"
},{
category: "History",
book: "B"
},{
category: "Science",
book: "C"
},{
category: "Science",
book: "C"
},{
category: "Science",
book: "C"
}];
// Step 1: Get the categories
const categories = Array.from(new Set(mongoData.map(x => x.category)));
// Step 2: Get combinations of those categories
const combos = [];
for(let i = 0; i < categories.length - 1; i++) {
let outerCat = categories[i];
for(let j = i + 1; j < categories.length; j++) {
let innerCat = categories[j];
combos.push([
outerCat,
innerCat
]);
}
}
// Step 3: Map the categories to the books that they contain
const catBooks = mongoData.reduce((map, entry) => {
map[entry.category] = map[entry.category] || new Set();
map[entry.category] = map[entry.category].add(entry.book);
return map;
}, {});
// Step 4: Get the duplicate books for each combo
combos.forEach((combo, index) => {
const cat1 = combo[0];
const cat2 = combo[1];
const cat1BooksArr = Array.from(catBooks[cat1]);
const cat2BooksSet = catBooks[cat2];
const dupes = cat1BooksArr.filter(book => {
return cat2BooksSet.has(book);
});
combos[index].push(dupes); // push into combos array
});
// Done! Your combos array contains arrays that look like this: [cat1, cat2, [dupes]]
combos.forEach(combo => {
console.log("Combo: " + combo[0] + ", " + combo[1]);
console.log("\tNumber of dupes: " + combo[2].length);
});
关于javascript - MongoDB - 查找一组文档之间的共同值计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47684435/