我使用official MongoDB driver作为Node.js.
这就是我的消息数据的结构。如您所见,每个帖子都有时间戳,userId和主题的ID。
[
{
"_id" : ObjectId("5b0abb48b20c1b4b92365145"),
"topicId" : "XN7iqmCFD4jpgJZ6f",
"timestamp" : 1527429960,
"user" : "5b0869636f4e363e300d105a",
"content" : "lorem ipsum"
}
]
现在我需要检查是否有主题,最新帖子(=最高时间戳)与我自己的ID不匹配。 有了这个,我确实知道哪个主题有一个新的答案(这不是我自己的帖子)。
所以我从这开始:
db.messages.find({
$query: {
user: { $ne: "myUserId" }
},
$orderby: {
timestamp: -1
}
}).limit(1).toArray()
我的问题是,我不知道如何通过topicId对我的查询进行分组。不知怎的,我的尝试似乎有错误的语法。
答案 0 :(得分:1)
您必须使用汇总按$sort
分组,然后$limit
按时间分类,然后db.messages.aggregate([
{ $match: { user: { $ne: "myUserId" } }},
{ $group: {
_id: "$topicId",
timestamp: { $first: "$timestamp"},
user: { $first: "$user" },
content: { $first: "$content" }
}},
{ $sort: { timestamp: -1 } },
{ $limit: 1 }
])
来限制查询
Artifacts >> Development (trigger on build success) >> Production (manual trigger after Development)
答案 1 :(得分:0)
使用聚合管道来代替查找。
1)$ match $ ne:" myUserId"
2)$ sort timestamp:-1
3)$ group topicId $ first
我过去写的一个示例查询..
Public Class CheckForDuplicateFiles
Private Sub btnDirectory_Click(sender As Object, e As EventArgs) Handles btnDirectory.Click
Directory.ShowDialog()
Dim SelectedDirectory As String = Directory.SelectedPath
Dim SourceDirectory As DirectoryInfo = New DirectoryInfo(SelectedDirectory)
Dim lstFiles As New List(Of FileData)
For Each childFile As FileInfo In SourceDirectory.GetFiles("*", SearchOption.AllDirectories).Where(Function(file) file.Extension.ToLower = cboExtensions.SelectedItem.ToString)
Dim hash As MD5
hash = MD5.Create
Dim hashvalue() As Byte
Dim filestream = childFile.OpenRead
hashvalue = hash.ComputeHash(filestream)
Dim has_hex1 As String = PrintByteArray(hashvalue)
Dim f As New FileData()
f.Name = Path.GetFileNameWithoutExtension(childFile.Name)
f.Size = childFile.Length
f.Extension = childFile.Extension
f.Hash = has_hex1
f.Location = childFile.FullName
f.AddedToListView = False
For i As Integer = 0 To lstFiles.Count - 1
If lstFiles.Item(i).Hash = f.Hash Then
AddToListView(f)
f.AddedToListView = True
If lstFiles.Item(i).AddedToListView = False Then
AddToListView(lstFiles.Item(i))
lstFiles.Item(i).AddedToListView = True
End If
Exit For
End If
Next
lstFiles.Add(f)
Next
End Sub
Private Sub AddToListView(file As FileData)
'Adding in ListView
Dim NewItem As ListViewItem = ListView1.Items.Add(file.Name)
NewItem.SubItems.Add(file.Size.ToString)
NewItem.SubItems.Add(file.Extension)
NewItem.SubItems.Add(file.Hash)
NewItem.SubItems.Add(file.Location)
End Sub
Private Function PrintByteArray(bytes As Byte()) As String
Dim sb As New StringBuilder
For Each b As Byte In bytes
sb.Append(b)
Next
Return sb.ToString
End Function
Public Class FileData
Public Property Name As String
Public Property Size As Long
Public Property Extension As String
Public Property Hash As String
Public Property Location As String
Public Property AddedToListView As Boolean
End Class
End Class