Answer the question
In order to leave comments, you need to log in
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]
}
Answer the question
In order to leave comments, you need to log in
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)
})
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"})
// 10 - ид записи
db.collection.find({$where: "this.articles.map(id => '' + id).indexOf(10) != -1"})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question