检索mongoDB中数组中的所有元素

met*_*uzz 2 mongodb meteor

如何将数组赋给变量.我能够返回我想要的文档,但不能专门获取特定字段内的数组中的所有元素.该字段称为"喜欢".

我的查询过滤我想要的文件:

Posts.find({}, {owner: Meteor.user()})
Run Code Online (Sandbox Code Playgroud)

我想从Posts集合中检索名为"likes"的数组字段中的所有元素.('likes'字段中的每个元素都是一个对象ID)

我尝试使用各种运算符,例如'all'字段中的$ all和$ in,并在console.log中进行测试,但我无法获得ID.根据mongo文档,我需要在运算符中指定一个元素,但我不希望这样.我只想要内心的任何东西.

var likers = Posts.find({}, {owner: Meteor.user()}, {likes: {$in: [] }})
Run Code Online (Sandbox Code Playgroud)

基本上,我试图从"喜欢"字段中检索所有元素,以便我可以进行另一个查询来返回结果.

我正在运行流星0.9+

Dav*_*don 5

尝试一下:

var myPosts = Posts.find(
  {owner: Meteor.user()},
  {fields: {likes: 1}}
).fetch()

var myLikes = _.chain(myPosts)
  .pluck('likes')
  .flatten()
  .uniq()
  .value();
Run Code Online (Sandbox Code Playgroud)

首先,我们获取当前用户所有者的所有帖子.每个帖子都包含一个_id和一个likes数组.接下来我们通过以下方式提取所有喜欢:

  1. 拔除每个likes从每个文档.这让我们得到了一个数组.
  2. 将数组数组展平为单个数组.
  3. 运行uniq所以我们只有独特的喜欢(不是必需的,但可能是一个优化).

然后myLikes,您可以在后续查询中使用.例如:

Likes.find({_id: {$in: myLikes}})
Run Code Online (Sandbox Code Playgroud)

以下是一些myPosts空的情况下的测试数据:

var myPosts = [
  {_id: 1, likes: [1, 2, 3]},
  {_id: 2, likes: [2, 3, 4]},
  {_id: 3, likes: [4, 5, 6]}
];
Run Code Online (Sandbox Code Playgroud)

在这种情况下myLikes将是:[ 1, 2, 3, 4, 5, 6 ]