$ setIntersection是否可以与对象一起使用? [英] Does $setIntersection work with objects?

查看:79
本文介绍了$ setIntersection是否可以与对象一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法获得$ setIntersection来处理对象.

I cant seem to get $setIntersection to work with objects.

示例:

对象1:

[
  {name: "test5", value:5},
  {name: "test4", value:4},
  {name: "test3", value:3},
  {name: "test2", value:2}
]

对象2:

[
  {name: "test5", value:5},
  {name: "test422", value:422},
  {name: "test333", value:3333},
  {name: "test211", value:211}
]

$ setIntersection将返回我[]而不是:

$setIntersection would return me [] instead of this:

[
  {name: "test5', value:5}
]

如果$ setIntersection无法与Objects一起使用,是否可以使用其他解决方法?

If $setIntersection does not work with Objects, is there any work around that I can use?

推荐答案

似乎您做错了:

如果我插入一个具有如下数组的对象:

If I insert an object with an array like so:

db.test.insert({
    "a" : [ 
        {
            "name" : "test5",
            "value" : 5.0
        }, 
        {
            "name" : "test4",
            "value" : 4.0
        }, 
        {
            "name" : "test3",
            "value" : 3.0
        }, 
        {
            "name" : "test2",
            "value" : 2.0
        }
    ]
})

然后我使用

And I run an .aggregate() with $setInsersection and the supplied array of objects like so:

db.getCollection('test').aggregate([
  { "$project": {
    "a": {
      "$setIntersection": [
        "$a",
        [
          {name: "test5", value: 5},
          {name: "test422", value: 422},
          {name: "test333", value: 3333},
          {name: "test211", value: 211}
        ]
      ]    
    }  
  }}
])

然后我得到了预期的结果:

Then I get the expected result:

/* 1 */
{
    "_id" : ObjectId("59f02df75b9b8bb266a563cb"),
    "a" : [ 
        {
            "name" : "test5",
            "value" : 5.0
        }
    ]
}

如果属性是反向的",例如:

If the properties are "reversed", as in:

db.getCollection('test').aggregate([
  { "$project": {
    "a": {
      "$setIntersection": [
        "$a",
        [
          { value: 5, name: "test5" },
          {name: "test422", value: 422},
          {name: "test333", value: 3333},
          {name: "test211", value: 211}
        ]
      ]    
    }  
  }}
])

然后结果数组为"empty",这应该是预期的,因为 {"name":"test5","value":5} {"value:5," test:名称} 涉及到集合".

Then the result array is "empty", as should be expected because { "name": "test5", "value": 5 } is not the same as { "value": 5, "test": name } as far as a "set" is concerned.

这篇关于$ setIntersection是否可以与对象一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆