您可以为此使用$elemMatch运算符。让我们创建包含文档的集合
> db.getDocumentsByTagsDemo.insertOne({"Tags":["Tag-1", "Tag-2", "Tag-3"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c9eb4d5d628fa4220163b79") } > db.getDocumentsByTagsDemo.insertOne({"Tags":["Tag-2", "Tag-4", "Tag-5"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c9eb4d5d628fa4220163b7a") } > db.getDocumentsByTagsDemo.insertOne({"Tags":["Tag-6", "Tag-4", "Tag-3"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c9eb4d6d628fa4220163b7b") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.getDocumentsByTagsDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9eb4d5d628fa4220163b79"), "Tags" : [ "Tag-1", "Tag-2", "Tag-3" ] } { "_id" : ObjectId("5c9eb4d5d628fa4220163b7a"), "Tags" : [ "Tag-2", "Tag-4", "Tag-5" ] } { "_id" : ObjectId("5c9eb4d6d628fa4220163b7b"), "Tags" : [ "Tag-6", "Tag-4", "Tag-3" ] }
以下是通过标签获取文档的查询
> db.getDocumentsByTagsDemo.find({Tags: { $elemMatch: { $eq: "Tag-2" } }}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9eb4d5d628fa4220163b79"), "Tags" : [ "Tag-1", "Tag-2", "Tag-3" ] } { "_id" : ObjectId("5c9eb4d5d628fa4220163b7a"), "Tags" : [ "Tag-2", "Tag-4", "Tag-5" ] }
以下是仅查找特定标签的查询
> db.getDocumentsByTagsDemo.find({Tags: "Tag-5"}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9eb4d5d628fa4220163b7a"), "Tags" : [ "Tag-2", "Tag-4", "Tag-5" ] }