A
A
Alexander2018-09-10 00:56:14
MongoDB
Alexander, 2018-09-10 00:56:14

How to compare array values ​​in mongo documents and find matches?

There is a collection in mongo with documents in the form

{
  _id: id,
  name: name,
  articles: [id1, id2, id3, id4]
}

For example, the id of three such documents came to the server on nodejs, how can I compare the arrays of articles of these three documents and find in them all the matching id between each other?
Unfortunately, I am very new to the mongo syntax, and I can’t figure out how to write it myself, but I guess that I need something like this https://stackoverflow.com/questions/30646534/how-t...
I will be glad for any help, thank!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2018-09-11
@IceDevil

As a result, I sorted out the error myself, maybe someone will need the
Nodejs + Mongo + Mongoose solution
For example - There is a set of articles, each article has several thematic tags.
It is required to sort by several simultaneously selected tags
Solution: when creating an article, add thematic tags to it. On the back, to each specified tag, add the id of the created article.
Now each tag in the database has an array with the id of all articles with this tag.
To get all articles containing several selected tags
We need to find these tags in the database, and find articles in their arrays, all matching id

// пример документа Тега
{
  _id: "5b93e8a9c2c6bf1cd44144a0",
  name: name,
  articles: [
    	'5b93e843c2c6bf1cd4414490',
      	'5b93e849c2c6bf1cd4414491',
      	'5b93e84dc2c6bf1cd4414492',
      	'5b93e852c2c6bf1cd4414493',
      	'5b93e857c2c6bf1cd4414494',
      	'5b93e85dc2c6bf1cd4414495',
      	'5b93e862c2c6bf1cd4414496',
      	'5b93e867c2c6bf1cd4414497',
  ]
}


// для примера это id тегов в базе получиные с клиента на бек
var tagsID [
  '5b93e8a9c2c6bf1cd44144a0',
  '5b93e8b4c2c6bf1cd44144a1',
  '5b93e8bac2c6bf1cd44144a2',
  '5b93e8c0c2c6bf1cd44144a3',
  '5b93e8c6c2c6bf1cd44144a4',
]


// https://stackoverflow.com/questions/30646534/how-to-find-set-intersection-of-sets-between-the-documents-in-a-single-collectio
// тут был описан код сортировки, и моя проблема была в том, что надо было преобразовать id тегов для mongoose
var convertTagsForAggregate = [];
for (var i = 0; i < tagsID.length; i++) {
  convertTagsForAggregate.push(mongoose.Types.ObjectId(tagsID[i]))
}

Tags.aggregate([
  {
    "$match": {
      "_id": { "$in": convertTagsForAggregate}
    }
  },
  {
    "$group": {
      "_id": 0,
      "sets": { "$push": "$articles" }, // articles - название ключа массива с id статей
      "initialSet": { "$first": "$articles" }  // articles - название ключа массива с id статей
    }
  },
  {
    "$project": {
      "commonSets": {
        "$reduce": {
          "input": "$sets",
          "initialValue": "$initialSet",
          "in": { "$setIntersection": ["$$value", "$$this"] }
        }
      }
    }
  }
], function (err, result) {
  console.log(result)
})

E
Evgeny Kumanin, 2018-09-10
@jackkum

If you do it in one request, then something like this:

// 1,2,3,10 - список идентификаторов
db.collection.find({$where: "[1,2,3,10].filter(id => (this.articles.map(id => '' + id).indexOf(id) != -1)).length > 0"})

such a request will be slow
Or one id at a time:
// 10 - ид записи
db.collection.find({$where: "this.articles.map(id => '' + id).indexOf(10) != -1"})

A
Andrey, 2018-09-10
@VladimirAndreev

_id came? So get them from mongo and compare on the client. So, most likely, it will turn out even faster than in mongo itself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question