【问题标题】:Meteor Mongo query for subset of array in collectionMeteor Mongo 查询集合中数组的子集
【发布时间】:2016-03-07 14:50:30
【问题描述】:

我在查询某些内容时遇到了问题。

我有一个名为 Guestlists 的集合,其中包含来宾列表。每个元素都包含一个日期和一些其他内容以及一个名为“列表”的数组。 “列表”数组包含每个来宾列表条目的元素。每个来宾列表条目都有一个“entryOwner”,表示将条目添加到列表中的人。

这是架构:

Schemas.Guestlist = new SimpleSchema({
  _id: { type: String, regEx: SimpleSchema.RegEx.Id },
  date: { type: Number },
  promoters: { type: [String], regEx: SimpleSchema.RegEx.Id, defaultValue: [] },
  list: { type: Array, defaultValue: [] },
  'list.$': { type: Object },
  'list.$.name': { type: String },
  'list.$.entryOwner': { type: String },
  'list.$.comment': { type: String, optional: true },
  'list.$.accepted': { type: Boolean, defaultValue: false },
  'list.$.rejected': { type: Boolean, defaultValue: false },
})

现在问题来了。我想查询数据库并获取 1 个访客列表,并且仅获取特定用户 ID 的访客列表条目。

这是我尝试过的:

Guestlists.find({_id : guestlistID, list: {$elemMatch: {entryOwner: user._id}}}, {fields: { 'list.$': 1}})

但是,这只会返回带有“列表”数组中的一项的来宾列表,这是第一项。如何获取“列表”中具有我查询的 entryOwner 的所有项目?

也试过了,但结果相同:

Guestlists.find({_id: guestlistID}, {fields: {list: {$elemMatch: {entryOwner: user._id}}}})

保留它作为光标也很重要,因为我想在我的出版物中返回它

【问题讨论】:

    标签: javascript arrays mongodb meteor


    【解决方案1】:

    这是你要找的吗?

     Guestlists.findOne({{_id : guestlistID, list: {$elemMatch: {entryOwner: user._id}}}};
    

    这将GuestLists 的返回数量限制为1。它作为对象返回,而不是长度为 1 的数组。

    【讨论】:

    • 不,这不是我要找的,找到了。很快就会发布!
    【解决方案2】:

    编辑 2016-03-08

    找到了如何解决整个问题的解决方案!

    现在我使用一个包 (https://atmospherejs.com/jcbernack/reactive-aggregate) 并完全按照他们的描述进行操作。

    在出版物中,我进行汇总,然后设置一个客户端集合,将数据推送到该集合。然后我订阅并从客户端集合中获取数据。


    好的,我从 Meteor 论坛获得了一些帮助。

    我一直在寻找的是在 MongoDB 中使用 Aggregate!它确实存在一个很好的包: https://github.com/meteorhacks/meteor-aggregate

    这就是我的代码现在的样子:

    guestList = Guestlists.aggregate([
        { $match: {nightclubId: nightclubId, date: dateTime}},
        { $unwind: '$list'},
        { $match: {'list.entryOwner': user._id}},
        { $group: {_id: '$_id', list: {$push: '$list'}}}
      ])
    

    现在我的问题是如何将这个从我的出版物返回给客户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 2020-01-13
      • 2017-04-05
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多