I'm trying to simulate a join in a mongo query so I'm taking the results of my 1st query and then passing it as a $in filter to my 2nd query.
我试图模拟mongo查询中的一个连接,所以我取第一个查询的结果,然后将它作为$in过滤器传递给第二个查询。
Unfortunately the results of my 1st query returns an array of json objects like so
不幸的是,第一个查询的结果返回一个json对象数组
[ { _id: 4ecd830da046050100000025 },
{ _id: 4ecd84a0a046050100000085 } ]
and the $in filter doesn't return anything because they are json objects instead of a value array. I can manually transform that array but is there a built in method or function that I can use? Also, is there a way I can have mongo return the value array instead? Currently I am calling the find query as such
$in过滤器不会返回任何东西,因为它们是json对象而不是值数组。我可以手动转换那个数组,但是有内置的方法或函数可以使用吗?另外,是否有办法让mongo返回值数组?目前我正在调用find查询
Likes.find {liker:"Me"}, {_id:1}, {safe:true}
And here is my 2nd query
这是我的第二个问题
Post.find {_id:{$in:likes}}
I was hoping for something like
我希望能有这样的机会。
Post.find {_id:{$in:likes._id}}
1 个解决方案
#1
3
Although there is no general solution to your question in the case of $in clauses you can use the result of a distinct operation :
虽然你的问题在$in条款中没有通用的解决方案,但你可以使用不同操作的结果:
> db.test.save({a:1})
> db.test.save({a:2})
> db.test.save({a:3})
> db.test.save({a:4})
> ids = db.test.distinct("_id", {a:{$gt:2}})
[
ObjectId("4ece45c2c951f11718678574"),
ObjectId("4ece45c4c951f11718678575")
]
> db.test.find({_id:{$in:ids}})
{ "_id" : ObjectId("4ece45c2c951f11718678574"), "a" : 3 }
{ "_id" : ObjectId("4ece45c4c951f11718678575"), "a" : 4 }
Hope that helps!
希望会有帮助!
#1
3
Although there is no general solution to your question in the case of $in clauses you can use the result of a distinct operation :
虽然你的问题在$in条款中没有通用的解决方案,但你可以使用不同操作的结果:
> db.test.save({a:1})
> db.test.save({a:2})
> db.test.save({a:3})
> db.test.save({a:4})
> ids = db.test.distinct("_id", {a:{$gt:2}})
[
ObjectId("4ece45c2c951f11718678574"),
ObjectId("4ece45c4c951f11718678575")
]
> db.test.find({_id:{$in:ids}})
{ "_id" : ObjectId("4ece45c2c951f11718678574"), "a" : 3 }
{ "_id" : ObjectId("4ece45c4c951f11718678575"), "a" : 4 }
Hope that helps!
希望会有帮助!