MongoDB - Aggregate $match on ObjectId

2020-07-13 08:21发布

问题:

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'},
});

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") }

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.

回答1:

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) {
   ...
});


回答2:

that does not work right now with versions > 3.8.31 i've wasted countless hours on that one, should have tested the earlier mayor sooner...