MongoDB-在ObjectId上聚合$ match [英] MongoDB - Aggregate $match on ObjectId
问题描述
我有一个看起来像这样的模式:
I have a schema that looks like this:
var mongoose = require('mongoose');
module.exports = mongoose.model('Owner',{
username: String,
blocks: {type:mongoose.Schema.Types.ObjectId, ref: 'Block'},
});
我正在尝试运行查询以查看所有者是否具有对Block ID的引用.所有者具有一个ObjectId数组.当我运行db.owners.aggregate({$match: {username: 'example'}},{$unwind: "$blocks"},{$project: { _id : 1,blocks: 1}})
时,它将返回:
I'm trying to run a query to see if Owner has a reference to Block's id. Owner has an array of ObjectIds. When I run db.owners.aggregate({$match: {username: 'example'}},{$unwind: "$blocks"},{$project: { _id : 1,blocks: 1}})
it returns:
{ "_id" : ObjectId("550d9dc64d9dc3d026fadfc7"), "blocks" : ObjectId("550dc117dc9605ab27070af7") }
{ "_id" : ObjectId("550d9dc64d9dc3d026fadfc7"), "blocks" : ObjectId("550dc123dc9605ab27070af8") }
{ "_id" : ObjectId("550d9dc64d9dc3d026fadfc7"), "blocks" : ObjectId("550dc12edc9605ab27070af9") }
{ "_id" : ObjectId("550d9dc64d9dc3d026fadfc7"), "blocks" : ObjectId("550dc157dc9605ab27070afa") }
如何匹配块ID?我已经尝试过db.publishers.aggregate({$match: {username: 'example'}},{$unwind: "$blocks"},{$project: { _id : 1,blocks: 1}},{$match : {"blocks._id" : '550dc157dc9605ab27070afa'}})
,但这不起作用.
How can I match the block id? I've tried db.publishers.aggregate({$match: {username: 'example'}},{$unwind: "$blocks"},{$project: { _id : 1,blocks: 1}},{$match : {"blocks._id" : '550dc157dc9605ab27070afa'}})
but that doesn't work.
推荐答案
我认为您不需要这样做,可以使用简单的find()
或findOne()
查询:
I think you don't need aggreation for that, you can use a simple find()
or findOne()
query:
var Mongoose = require('mongoose');
var ObjectId = Mongoose.Types.ObjectId;
Owner.findOne({ username: 'example', blocks: new ObjectId('550dc157dc9605ab27070afa') }, function (err, owner) {
...
});
这篇关于MongoDB-在ObjectId上聚合$ match的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!