如何根据名称列表获取 MongoDB 查询结果中的标签计数?
你可以使用 $in 运算符。我们首先使用文档创建一个集合 -
> db.tagCountDemo.insertOne({"ListOfNames":["John","Sam","Carol"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd64b387924bb85b3f48944") } > db.tagCountDemo.insertOne({"ListOfNames":["Bob","David","John"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd64b4b7924bb85b3f48945") } > db.tagCountDemo.insertOne({"ListOfNames":["Mike","Robert","Chris"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd64b5d7924bb85b3f48946") } > db.tagCountDemo.insertOne({"ListOfNames":["James","Carol","Jace"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd64b717924bb85b3f48947") }
以下查询可通过 find() 方法显示集合中的所有文档 -
> db.tagCountDemo.find().pretty();
这将生成以下输出 -
{ "_id" : ObjectId("5cd64b387924bb85b3f48944"), "ListOfNames" : [ "John", "Sam", "Carol" ] } { "_id" : ObjectId("5cd64b4b7924bb85b3f48945"), "ListOfNames" : [ "Bob", "David", "John" ] } { "_id" : ObjectId("5cd64b5d7924bb85b3f48946"), "ListOfNames" : [ "Mike", "Robert", "Chris" ] } { "_id" : ObjectId("5cd64b717924bb85b3f48947"), "ListOfNames" : [ "James", "Carol", "Jace" ] }
以下是获取 MongoDB 中标签计数的查询
> db.tagCountDemo.find({"ListOfNames":{$in:['John','Carol']}});
这将生成以下输出 -
{ "_id" : ObjectId("5cd64b387924bb85b3f48944"), "ListOfNames" : [ "John", "Sam", "Carol" ] } { "_id" : ObjectId("5cd64b4b7924bb85b3f48945"), "ListOfNames" : [ "Bob", "David", "John" ] } { "_id" : ObjectId("5cd64b717924bb85b3f48947"), "ListOfNames" : [ "James", "Carol", "Jace" ] }
广告