Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to check if an array field contains a unique value or another array in MongoDB?

I am using mongodb now.

I have a blogpost collection, and it has a tags field which is an array, e.g.

blogpost1.tags = ['tag1', 'tag2', 'tag3', 'tag4', 'tag5']
blogpost2.tags = ['tag2', 'tag3']
blogpost3.tags = ['tag2', 'tag3', 'tag4', 'tag5']
blogpost4.tags = ['tag1', 'tag4', 'tag5']

How can I do these search

  1. contains tag1
  2. contains ['tag1','tag2']
  3. contains any of ['tag3', 'tag4']
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Try this out:

db.blogpost.find({ 'tags' : 'tag1'}); //1
db.blogpost.find({ 'tags' : { $all : [ 'tag1', 'tag2' ] }}); //2
db.blogpost.find({ 'tags' : { $in : [ 'tag3', 'tag4' ] }}); //3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...