如何将文档附加到子文档数组中 - Java/MongoDB [英] How to append document into sub-document array - Java/MongoDB
问题描述
如何使用 Java 将新文档附加到 MongoDB 上的子文档数组?
How can I append a new document to sub-document array on MongoDB with Java?
例如,将 {tweetId : 456} 附加到文档tweets"数组:
For exemple, append {tweetId : 456} to the array of documents "tweets":
{
day : 20170209,
hours : {
hour : 20,
tweets : {tweetId : 123 }
}
}
想要的结果:
{
day : 20170209,
hours : [ {hour : 20,
tweets : [{tweetId : 123},{tweetId : 456}]},
{hour : 21,
tweets : [{tweetId : 567},{tweetId : 890}]}
]
}
更新
对不起,我没有正确解释,tweet 文档是一个 tweetsId 数组.我修正了上面的例子以便更好地理解.
Sorry, I didn't explain correctly, the tweets document is an Array of tweetsId. I fixed the above example to better understanding.
例如,只有 2 个级别的集合:
For example, with a collection with only 2 levels:
{
"_id":{
"$oid":"589c5a1047e9062f004b84a3"
},
"hashtag":"BRASIL",
"tweets":[
{
"tweetId":"829661297121845249"
},
{
"tweetId":"829661278352269313"
}
]
}
我可以将一个新的 TweetId 附加到这个数组:
I can append a new TweetId to this array with:
collection.updateOne(new Document("hashtag", hashtag),
new Document("$push", new Document("tweets", new Document("tweetId", tweetId))));
但是当数组处于第 3 级(小时 > 推文 > TweetId)时,我找不到正确的方法.
But when the array is at level 3 (Hours > Tweets > TweetId), I can't find a way to do it correctly.
希望现在解释得更好.
推荐答案
通过 Riccardo 发送的提示,我查看了如何使用聚合函数并能够获得我需要的结果,而无需按小时为推文创建集合.
with the tip sent by Riccardo, I look how to use the aggregation function and was able to get the result that I needed without creating a collection for tweets by hour.
我使用了包含所有推文及其详细信息的集合,并使用以下函数检索数据:
I used the collection that had all the tweets with its details, and with the function below, was able to retrieve the data:
tweetsCol.aggregate([
{$group: {_id : {Date : "$date", Hour : '$hour'}, Total : {$sum : 1}}}
])
我的推文集包含以下信息:
My collection of tweets has the following information:
"tweetId" : String,
"userId" : String,
"username" : String,
"followers" : String,
"language" : String,
"fulldate" : String,
"date" : String,
"hour" : String,
"text" : String,
"hashtags" : [{
"tweetId" : String
}]
查询结果:
[{Date : 20170209,
hours : [{hour : 21, Total: 45},
{hour : 22, Total: 22}]},
{Date : 20170210,
hours : [{hour : 11, Total: 38},
hour : 17, Total : 71}]
]
这篇关于如何将文档附加到子文档数组中 - Java/MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!