我有一些包含tags
数组的文档。我想在网站上提供基于标签的推荐,所以我需要获取包含相同标签的文档+不匹配1个标签的文档+不匹配2个标签等等...
我该如何做到这一点?
示例集合:
db.tags.insert({"tags":["red", "tall", "cheap"]});
db.tags.insert({"tags":["blue", "tall", "expensive"]});
db.tags.insert({"tags":["blue", "little", "cheap"]});
找出所有包含标签"blue"的内容
db.tags.find({tags: { $elemMatch: { $eq: "blue" } }})
查找所有标记为“blue”的内容,且只包含蓝色的。
db.tags.find({tags: "blue"})
查找所有被标记为“蓝色”和“便宜”的项目
db.tags.find({ tags: { $all: ["cheap", "blue"] } } )
查找所有非“蓝色”的
db.tags.find({tags: { $ne: "blue" } })
查找所有“蓝色”和“便宜”的但不包括“红色”和“高个子”的内容。
在我的MongoDB中无法实现。从MongoDB 1.9.1开始,应该可以像这样工作(未经测试):
db.tags.find({ $and: [ {tags: { $all: ["blue", "cheap"] } }, { tags: { $nin: ["red", "tall"] } } ] })
$in
操作符查找一些但不是全部,这个答案让我误以为$all
的行为类似于$in
。https://docs.mongodb.org/v3.0/reference/operator/query/in/#op._S_in - nak[{_id : ObjectId(1249999493),tags : ['Location1', 'SkillSet1', 'SkillSet2', 'Someother1', 'Someother2']},
{_id : ObjectId(1249999494),tags : ['Location3', 'SkillSet1', 'SkillSet0', 'Someother4', 'Someother3']}]
步骤:
查找包含任何指定关键字的匹配产品。
在关键字上展开
再次查找以过滤展开后不需要的内容
通过添加关键字出现次数对它们进行分组
按降序排序以获取最相关的结果
[{ "$match" : { "keys" : { "$in" : [ { "$regex" : "text" , "$options" : "i"}]}}}, { "$unwind" : "$keys"}, { "$match" : { "keys" : { "$in" : [ { "$regex" : "text" , "$options" : "i"}]}}}, { "$group" : { "_id" : { "productId" : "$productId"} , "relatedTags" : { "$sum" : 1} }}, { "$sort" : { "relatedTags" : -1}},{ "$limit" : 10}]