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
888 views
in Technique[技术] by (71.8m points)

mongoose - How We combine two query in MongoDB $in and $nin with same condition?

I want to combine the result of $in query with $nin query and want the final result. So how we can do this using one mongo query? is there is any way to do it? For e.g., I have the following documents in the user collection:

[{
    name:"test",
    "uid":123
},{
    name:"test1",
    "uid":124
},{
    name:"test2",
    "uid":125
},{
    name:"test3",
    "uid":126
},{
    name:"test3",
    "uid":127
}]

and I want the following result:

[{
    name:"test2",
    "uid":125
},{
    name:"test3",
    "uid":126
},{
    name:"test",
    "uid":123
},{
    name:"test3",
    "uid":127
}]

Basically I want uid:125 and uid:126 on first two position ignore about their sequence and then uid:123 and uid: 127 on 3rd and 4th position ignore about their sequence. So I am doing this by following two query

  1. db.getCollection('user').find({uid:{$in:[125,126]}})

  2. db.getCollection('user').find({uid:{$nin:[125,126]}})

and then I am combining the result but How I can do this in the same query? I have so many documents it is just example so need to combine the result of $in and $nin query

How I can do this?


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

1 Reply

0 votes
by (71.8m points)

There is no straight way to do this, I have recently answered here, almost similar question,

  • You need to use aggregation query, try $cond will check if uid in array [125, 126] then return 1 otherwise 0 in matchResult,
  • $sort by matchResult in descending order
db.getCollection('user').aggregate([
  {
    $addFields: {
      matchResult: {
        $cond: [{ $in: ["$uid", [125, 126]] }, 1, 0]
      }
    }
  },
  { $sort: { matchResult: -1 } }
])

Playground


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

...