MongoDB:如何在单个查询中过滤从$ne/$eq运算符返回的真/假结果



这里 可能的双重,但没有多大用处。

我有这样的收藏

    {
       "_id": {
           "$oid": "589764fb40948e196cc90e8a"
       },
       "color": "red",
       "tweets": ["I am fine", "I am ok"],
       "userId": "172884537",
       "tweetIds": ["819223623735119873", "819219362049572864"]
   } {
       "_id": {
           "$oid": "589764fb40948e196cc90e8b"
       },
       "color": "red",
       "tweets": ["How are you?", "Where are you"],
       "userId": "4558206579",
       "tweetIds": ["822916538596462592"]
   } {
       "_id": {
           "$oid": "589764fb40948e196cc90e8c"
       },
       "color": "blue",
       "tweets": ["Whats up?", "Good night"],
       "userId": "1893540588",
       "tweetIds": ["822947258186403840", "822498809808728064"]
   } {
       "_id": {
           "$oid": "589764fb40948e196cc90e8d"
       },
       "color": "red",
       "tweets": ["trump"],
       "userId": "781950015858176001",
       "tweetIds": ["819486328467374081", "819220448282079233"]
   }

我想获取那些推文数量和推文数量不相等的用户ID。

我尝试了两种方式

    db.us_election_nodes_with_tweets.aggregate([{
     "$project": {
         "_id": 1,
         "alloc": {
             "$ne": [{
                 "$size": "$tweets"
             }, {
                 "$size": "$tweetIds"
             }]
         }
     }
 }, {
     "$match": {
         "alloc": 1
     }
 }])

而另一个

db.us_election_nodes_with_tweet.find({
    $and: [{
        result: {
            "$ne": [{
                $size: "$tweets"
            }, {
                $size: "$tweetIds"
            }]
        }
    }, {
        result: {
            $exists: true
        }
    }]
}).pretty()

如果我这样做

    db.us_election_nodes_with_tweet.aggregate([{
     $project: {
         _id: 0,
         userId: 1,
         result: {
             "$ne": [{
                 $size: "$tweets"
             }, {
                 $size: "$tweetIds"
             }]
         }
     }
 }])

我得到这样的输出。因为$ne返回 true,所以它不匹配,在匹配的地方返回 false。

{ "userId" : "172884537", "result" : false }
{ "userId" : "781950015858176001", "result" : true}
{ "userId" : "4558206579", "result" : true }
{ "userId" : "1893540588", "result" : false }

但是在这里我不知道如何从这个结果中只过滤布尔值 true。你有什么建议吗?

更改$match以检查true

db.us_election_nodes_with_tweets.aggregate([ { "$project": { "_id": 1, "userId":1, "alloc": { "$ne": [ { "$size": "$tweets" }, { "$size": "$tweetIds" } ] } }}, { "$match": { "alloc": true } } ])

或者,您可以使用$redact当数组大小与行$$KEEP其他大小匹配时$$PRUNE

db.us_election_nodes_with_tweet.aggregate([{
    "$redact": {
        "$cond": [{
                 "$eq": [ { "$size": "$tweets" }, { "$size": "$tweetIds" } ]
            },
            "$$PRUNE",
            "$$KEEP"
        ]
    }
}])