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

时间:2017-02-06 20:22:39

标签: arrays mongodb arraylist

这里Possible duplicaion但没什么用处。

我有一个像这样的集合

    {
       "_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"]
   }

我想获得那些推文数量和tweetsIds数量不相等的userId。

我试过两种方式

    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。你有什么建议吗?

1 个答案:

答案 0 :(得分:1)

更改$match以检查true

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

作为替代方案,您可以使用$redact,当数组大小与行$$PRUNE匹配时$$KEEP

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