Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

Matching an array field which contains any combination of the provided array in MongoDB

I would like to query with a specified list of array elements such that documents returned can only contain the elements I pass, but need not contain all of them.

Given documents like:

{
  name: "Article 1",
  tags: ["Funny", "Rad"]
}

{
  name: "Article 2",
  tags: ["Cool", "Rad"]
}

{
  name: "Article 3",
  tags: ["Rad"]
}

Here are some example arrays and their respective results.

  • ["Rad"] should return Article 3
  • ["Rad", "Cool"] should return Article 2 and Article 3
  • ["Funny", "Cool"] should return nothing, since there are no articles with only one of those tags or both

I'm sure I can pull this off with $where but I'd like to avoid that for obvious reasons.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this by combining multiple operators:

db.test.find({tags: {$not: {$elemMatch: {$nin: ['Rad', 'Cool']}}}})

The $elemMatch with the $nin is finding the docs where a single tags element is neither 'Rad' nor 'Cool', and then the parent $not inverts the match to return all the docs where that didn't match any elements.

However, this will also return docs where tags is either missing or has no elements. To exclude those you need to add a qualifier that ensures tags has at least one element:

db.test.find({
    tags: {$not: {$elemMatch: {$nin: ['Rad', 'Cool']}}},
    'tags.0': {$exists: true}
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...