我有包含 tags
数组的文档。我想在网站上提供基于标签的建议,所以我需要获取包含相同标签的文档 + 不匹配 1 个标签的文档 + 不匹配 2 个标签的文档等等......
我该怎么做?
最佳答案
示例集合:
db.tags.insert({"tags":["red", "tall", "cheap"]});
db.tags.insert({"tags":["blue", "tall", "expensive"]});
db.tags.insert({"tags":["blue", "little", "cheap"]});
找出所有包含“蓝色”标签的内容
db.tags.find({tags: { $elemMatch: { $eq: "blue" } }})
找到所有标记为“蓝色”的,只有蓝色的
db.tags.find({tags: "blue"})
找到所有标记为“蓝色”和“便宜”的东西
db.tags.find({ tags: { $all: ["cheap", "blue"] } } )
找出所有不是“蓝色”的
db.tags.find({tags: { $ne: "blue" } })
找到所有“蓝色”和“便宜”,但不是“红色”而不是“高”
在我的 mongo 数据库中不可能。从 mongodb 1.9.1 开始,这样的东西应该可以工作,虽然(未经测试):
db.tags.find({ $and: [ {tags: { $all: ["blue", "cheap"] } }, { tags: { $nin: ["red", "tall"] } } ] })
关于MongoDB:按标签获取文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6940503/