我正在使用mongodb创建twitter克隆,并希望搜索其中包含特定主题标签的推文。我想出了我的数据库的以下文档结构 -
{
"_id" : ObjectId("56f88c038c297eb4048e5dff"),
"twitterHandle" : "abhayp",
"firstName" : "Abhay",
"lastName" : "Pendawale",
"emailID" : "abhayp@gmail.com",
"password" : "278a2c36eeebde495853b14e6e5525fd12074229",
"phoneNumber" : "12394872398",
"location" : "San Jose",
"birthYear" : 1992,
"birthMonth" : 0,
"birthDay" : 1,
"followers" : [
"abhayp",
"deepakp",
"john",
"madhuras",
"nupurs",
"vgalgali"
],
"following" : [
"abhayp",
"abhinavk",
"ankitac",
"anupd",
"arpits"
],
"tweets" : [
{
"tweet_id" : "3f0fe01f8231356f784d07111efdf9d8ead28133",
"tweet_text" : "This new twitter sounds good!",
"created_on" : ISODate("2016-03-13T01:47:37Z"),
"firstName" : "Abhay",
"lastName" : "Pendawale",
"twitterHandle" : "abhayp",
"tags" : [ ]
},
{
"tweet_id" : "4e57b6d7d6b47d69054f0be55c238e8038751d84",
"tweet_text" : "#CMPE273 Node.js is #awesome",
"created_on" : ISODate("2016-03-07T23:16:39Z"),
"firstName" : "Abhay",
"lastName" : "Pendawale",
"twitterHandle" : "abhayp",
"tags" : [
"awesome",
"CMPE273"
]
},
{
"tweet_id" : "e5facd5f37c44313d5be02ffe0a3ca7190affd6b",
"tweet_text" : "Getting an incredible welcome in #Pune #travel #adventure #film #india ",
"created_on" : ISODate("2016-03-07T23:37:27Z"),
"firstName" : "Abhay",
"lastName" : "Pendawale",
"twitterHandle" : "abhayp",
"tags" : [
"adventure",
"film",
"india",
"Pune",
"travel"
]
},
{
"tweet_id" : "f5a735c1f747732f3e04f6cb2c092ff44750c0fd",
"tweet_text" : "The D Day today!\n#TheDDay",
"created_on" : ISODate("2016-03-18T22:24:57Z"),
"firstName" : "Abhay",
"lastName" : "Pendawale",
"twitterHandle" : "abhayp",
"tags" : [ ]
}
]}
我想找出有" Pune"的推文。在推文的tags
数组中。我尝试了下面的命令
db.users.find({ "tweets.tags" : {$all: ["Pune"] }}, { tweets : 1 }).pretty();
但是这个命令会返回所有有' Pune'输入其中一条推文的标签。如何只搜索那些有“Pune'在tags
数组中输入?
注意:我不想要发送#Pune的用户,而是希望所有包含#Pune的推文。重复标记的问题无法解决此问题。
运行以下查询 -
db.users.aggregate([{
$match: {
'tweets.tags': 'Pune'
}
}, {
$project: {
tweets: {
$filter: {
input: '$tweets',
as: 'tweet',
cond: {
$eq: ['$$tweet.tags', 'Pune']
}
}
}
}
}]);
返回以下结果 -
{ "_id" : ObjectId("56f88c038c297eb4048e5df1"), "tweets" : [ ] }
{ "_id" : ObjectId("56f88c038c297eb4048e5dff"), "tweets" : [ ] }
{ "_id" : ObjectId("56f88c038c297eb4048e5e07"), "tweets" : [ ] }
这当然不是我想要的! :(
答案 0 :(得分:0)
除了使用一些复杂的聚合阶段之外,我认为这是不可能的。
projection operator已关闭但仅返回第一场比赛。
我的建议是将推文放在一个单独的集合中,浏览它们会更方便,而且可能更具可扩展性。您已经在其中复制了相关的用户信息,因此您无需更改其内容。