简体   繁体   中英

How to get the element in the array in mongoose/mongodb except the element we passed?

Here is the structure of a document of the collection Conversations . It contains participants array in an object which is inside messages array. Messages array contains several message objects like this :

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

Here I am having the messages.from data and I want to get the element from the messages.participants array except messages.from element.

In the above example from is 5530af38576214dd3553331c .So I have to get the element 553f280040d50ef20f8c9d66 from the messages.participants array.

There are several documents like the above and for each document we have to do the same.

How can I do that in moongoose / mongodb ?

Mongo aggregation and $unwind use to check whether your criteria match check following query :

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()

One approach you could do is use lodash library and in particular you'd want the difference method. This creates an array excluding all values of the provided arrays using SameValueZero for equality comparisons. Note: SameValueZero comparisons are like strict equality comparisons, eg === , except that NaN matches NaN .

So you could try the following:

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"]
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM