获取位于mongodb中的数组中的子文档的结果

时间:2017-05-18 06:46:53

标签: mongodb

让我们说我在mongodb中有一个名为users的数据库集合,文档如下所示:

[{
  _id: 'userId1'
  actions: [{
    name: 'SingUp',
    data: '...',
    time: '1'
  }, {
    name: 'CreatePost',
    data: '...',
    time: '4'
  }]
}, {
  _id: 'userId2'
  actions: [{
    name: 'SingUp',
    data: '...',
    time: '2'
  }, {
    name: 'CreatePost',
    data: '...',
    time: '3'
  }, {
    name: 'CreatePost',
    data: '...',
    time: '5'
  }]
}]

获取名称为CreatePost的操作文档的最有效方法是什么,所有操作文档都按时间排序?即我想要的结果是:

[{
  name: 'CreatePost',
  data: '...',
  time: '3'
}, {
  name: 'CreatePost',
  data: '...',
  time: '4'
}, {
  name: 'CreatePost',
  data: '...',
  time: '5'
}]

1 个答案:

答案 0 :(得分:1)

快速解决方案是使用 db.users.aggregate([ {$unwind: "$actions"}, {$match: {"actions.name": "CreatePost"}}, {$project: {"name": "$actions.name", "data": "$actions.data", "time": "$actions.time"}}, {$sort: {"time": 1}} ]) ,过滤掉 RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} /(mypage2(/.*)|about-us) # you used mypage2, so it will be redirected to subsite/#/mypage2 RewriteRule ^(.+)$ /subsite/#/$1 [R=301,NC] # Removes index.php from ExpressionEngine URLs RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC] RewriteCond %{REQUEST_URI} !/system/.* [NC] RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L] RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] # Directs all EE web requests through the site index file RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?/#/$1 [L,QSA] 的文档,最后使用 CopyOnWriteArrayList进行排序像这样:

;