【问题标题】:How to get the element in the array in mongoose/mongodb except the element we passed?如何在mongoose/mongodb中获取数组中除了我们传递的元素之外的元素?
【发布时间】:2015-07-09 18:52:10
【问题描述】:

这里是集合Conversations 的文档结构。 它在消息数组内的对象中包含参与者数组。 Messages 数组包含多个消息对象,如下所示:

{
  "_id": "5540b34347fdd4e917b80aa4",
  "messages": [{
    "from": "5530af38576214dd3553331c",
    "_id": "5540d5dc22f922061f68a41d",
    "participants": ["5530af38576214dd3553331c", "553f280040d50ef20f8c9d66"]
  }]
}

这里我有messages.from 数据,我想从messages.participants 数组中获取元素,但messages.from 元素除外。

在上面的例子中from5530af38576214dd3553331c。所以我必须从messages.participants数组中获取元素553f280040d50ef20f8c9d66

有几个类似上面的文档,对于每个文档,我们都必须这样做。

我怎样才能在 moongoose / mongodb 中做到这一点?

【问题讨论】:

  • 请改进问题的格式。如果您的问题是真实且可以理解的,那么您会从社区获得良好而快速的回复。

标签: node.js mongodb mongoose


【解决方案1】:

您可以做的一种方法是使用lodash 库,特别是您需要difference 方法。这将创建一个数组,不包括使用SameValueZero 提供的数组的所有值进行相等比较。注意:SameValueZero 比较类似于严格相等比较,例如===,除了 NaN 匹配 NaN

所以你可以尝试以下方法:

Conservations.where("_id": "5540b34347fdd4e917b80aa4")
    .select({"messages": { "$elemMatch": {"from": "5530af38576214dd3553331c"}})
    .exec(function (err, docs){
        var set_difference = _.difference(["5530af38576214dd3553331c"], docs[0].messages.participants);
        console.log(set_difference); // => ["553f280040d50ef20f8c9d66"]
    });

【讨论】:

    【解决方案2】:

    Mongo aggregation$unwind 用于检查您的条件是否匹配检查以下查询:

    db.collectionName.aggregate({
      "$unwind": "$messages" // first unwind messages array 
    }, {
      "$match": {
        "messages.from": "5530af38576214dd3553331c" //match critreia 
      }
    }, {
      "$unwind": "$messages.participants" // unwind participants array 
    }, {
      "$match": {
        "messages.participants": {
          "$ne": "5530af38576214dd3553331c" // check messages.from not equals participants array  
        }
      }
    }, {
      "$project": {
        "_id": 0,
        "participants": "$messages.participants"
      }
    }).pretty()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      相关资源
      最近更新 更多